7

React Router リンクをテストするための良い解決策を見つけるという悪夢に悩まされています。「カテゴリを適切にレンダリング」を渡していますが、テストに渡されるリンクはありません。さまざまなことを試しましたが、まだどこにも行きません。

以下は私がテストしようとしているものです:

成分

import React from 'react';
import { Link } from 'react-router';

class Categories extends React.Component {

constructor(props, context){
    super(props);
    context.router
}

render() {
    return (
        <nav className="categories">
          <ul>
              <li><Link to="devices">Devices</Link></li>
              <li><Link to="cases">Cases</Link></li>
              <li><Link to="layouts">Layouts</Link></li>
              <li><Link to="designs">Designs</Link></li>
          </ul>
        </nav>
    );
  }
}

Categories.contextTypes = {
 router: React.PropTypes.func.isRequired
};

export default Categories;

StubRouterContext

import React from 'react';
import objectAssign from 'object-assign';

var stubRouterContext = (Component, props, stubs) => {
function RouterStub() { }

objectAssign(RouterStub, {
  makePath () {},
  makeHref () {},
  transitionTo () {},
  replaceWith () {},
  goBack () {},
  getCurrentPath () {},
  getCurrentRoutes () {},
  getCurrentPathname () {},
  getCurrentParams () {},
  getCurrentQuery () {},
  isActive () {},
  getRouteAtDepth() {},
  setRouteComponentAtDepth() {}
 }, stubs)

return React.createClass({
childContextTypes: {
    router: React.PropTypes.func,
    routeDepth: React.PropTypes.number
},

getChildContext () {
    console.log('blah');
  return {
    router: RouterStub,
    routeDepth: 0
  };
},

render () {
  return <Component {...props} />
}
});
};

export default stubRouterContext;

コンポーネントテスト

var expect = require('chai').expect;

var React = require('react/addons');
var Categories = require('../app/src/js/components/Categories.React.js');
var stubRouterContext = require('../test-utils/stubRouterContext.js');
var TestUtils = React.addons.TestUtils;

describe('Categories', function() {
  var categoriesWithContext = stubRouterContext(Categories);

  it('renders Categories properly', function() {
  var categories = TestUtils.renderIntoDocument(<categoriesWithContext />, {});
});

it('renders 4 links', function() {
  var catLinks = TestUtils.scryRenderedDOMComponentsWithTag(categoriesWithContext, 'a');
  expect(catLinks).to.have.length(4);
});
});
4

2 に答える 2

1

私はまったく同じ問題を抱えていました。最新バージョンの react-router では、リンク要素をレンダリングするためにコンテキストは必要ないため、これは問題になりません。ただし、私のように API 1.0 より前のバージョンに固執している場合は、stubRouterContext アプローチがうまく機能します。

OP と私が見つけた唯一の理由は、ラッパーが空でレンダリングされていたことです。キャメルケースのコンポーネント名を使用しているためです。

var categoriesWithContext = stubRouterContext(Categories);になりvar CategoriesWithContext = stubRouterContext(Categories);ます。

したがってvar categories = TestUtils.renderIntoDocument(<categoriesWithContext />,{});となりvar categories = TestUtils.renderIntoDocument(<CategoriesWithContext />,{});ます。

このアプローチの説明はこちらです - https://gist.github.com/sebmarkbage/f1f4ba40816e7d7848ad

于 2015-08-27T09:49:57.527 に答える