使用react-router v4,Jest和Enzyme测试组件

时间:2017-03-31 14:39:32

标签: javascript reactjs react-router jestjs

我有一个使用react-router的简单组件(我知道这是alpha版本):

{props.app && props.app.health &&
   <Match exactly pattern="/" component={HomeLogin} />
}

文档建议在<MemoryRouter />中包装,以便在测试时为组件提供上下文。

但是,使用Jest / Enzyme我无法shallow()渲染 - 我必须使用酶mount()render(),这会导致问题,因为HomeLogin是一个连接组件 - 我希望能够测试我的组件呈现正确的东西,但测试在其中呈现的组件。

我的测试:

it('Renders based upon matched route', () => {
  let props = {
    app: { health: true },
  };
  const component = render(
    <Provider store={store}>
      <MemoryRouter location="/">
        <Jumbotron {...props} />
      </MemoryRouter>
    </Provider>
  );
  expect(toJson(component)).toMatchSnapshot();
});

如何根据路线测试此组件的输出,而无需提供redux存储或使用浅渲染?

更新:如果我尝试使用shallow(),则快照不会显示输出。

1 个答案:

答案 0 :(得分:1)

您可以使用.find(Jumbotron)并将其用作匹配快照,例如:

const wrapped = component.find(Jumbotron);
expect(toJson(wrapped)).toMatchSnapshot();

我有一个涉及withRouter()的更复杂的示例,我正在恢复以在匹配为快照之前从输出中删除所有键。好吧,直到测试React-Router v4在Jest和快照测试中变得更加稳固。例如:

export function removeKeys(object) {
    if (object === undefined || object === null) {
        return object;
    }
    Object.keys(object).forEach((key) => {
        if (typeof object[key] === 'object') {
            removeKeys(object[key]);
        } else if (key === 'key') {
           delete object[key];
        }
    });
    return object;
}

...

expect(removeKeys(toJson(component))).toMatchSnapshot();