我正在尝试测试我的NavComponent并遵循本指南https://medium.freecodecamp.org/the-right-way-to-test-react-components-548a4736ab22,但由于嵌套了<Link />
个组件,我需要将我的NavComponent安装在路由器中,如下所示:
import React from "react";
import { mount } from "enzyme";
import { StaticRouter } from 'react-router'
import Nav from './Nav';
describe("Nav", () => {
let props;
let mountedNav;
const nav = () => {
if (!mountedNav) {
mountedNav = mount(
<StaticRouter location="/">
<Nav />
</StaticRouter>
);
}
return mountedNav;
}
beforeEach(() => {
props = {
isMenuOpen: false
};
mountedNav = undefined;
});
// All tests go here
});
调用beforeEach()
时,我想设置<Nav />
的道具,而不是包装的路由器组件。
我无法通过酶像这样对子元素进行setProps:
nav().find('aside').setProps({isMenuOpen: false})
因为我会收到以下错误:
ReactWrapper::setProps() can only be called on the root
答案 0 :(得分:1)
我需要将beforeEach()
中生成的道具传递给<Nav>
组件。
const nav = () => {
if (!mountedNav) {
mountedNav = mount(
<StaticRouter location="/">
<Nav {...props} />
</StaticRouter>
);
}
return mountedNav;
}