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

标签 javascript reactjs react-router jestjs

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

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

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

但是,使用 Jest/Enzyme 我无法 shallow()渲染 - 我必须使用 enzyme 的 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 store 或使用浅层渲染的情况下根据路由测试此组件的输出?

更新:如果我尝试使用 shallow()快照不呈现任何输出。

最佳答案

您可以使用 .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();

关于javascript - 使用 react-router v4、Jest 和 Enzyme 测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143413/

相关文章:

node.js - jwt token 如何确保数据库更改时更新有效负载

reactjs - getDerivedStateFromProps 可以用作 componentWillReceiveProps 的替代品吗

javascript - 如何使用css3 translate移动到绝对位置

javascript - 使用 websockets 的 Web 应用程序 “Could not establish connection. Receiving end does not exist."

javascript - 自定义 Google Map API V3 缩放按钮

javascript - 当从 Promise 转发时,React Router 会重定向回来

javascript - 了解 React Router 参数

javascript - 使用 Firefox 将 JavaScript 控制台记录到日志文件中

reactjs - React Js 和 Chart Js(折线图)

node.js - 是否可以在React App路径下托管Wordpress博客