预计:
测试运行和状态在Login组件中更新,然后启用Notification组件(错误消息)
结果:
测试失败,预期1,收到0
最初在我添加redux和商店之前,因此需要在我的测试中使用商店和提供者逻辑,这个Jest / Enzyme测试正在通过 .
Login.test(更新当前版本)
import React from 'react'
import { Provider } from "react-redux"
import ReactTestUtils from 'react-dom/test-utils'
import { createCommonStore } from "../../store";
import { mount, shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import { missingLogin } from '../../consts/errors'
// import Login from './Login'
import { LoginContainer } from './Login';
import Notification from '../common/Notification'
const store = createCommonStore();
const user = {
id: 1,
role: 'Admin',
username: 'leongaban'
};
const loginComponent = mount(
<Provider store={store}>
<LoginContainer/>
</Provider>
);
const fakeEvent = { preventDefault: () => '' };
describe('<Login /> component', () => {
it('should render', () => {
const tree = toJson(loginComponent);
expect(tree).toMatchSnapshot();
});
it('should render the Notification component if state.error is true', () => {
loginComponent.setState({ error: true });
expect(loginComponent.find(Notification).length).toBe(1);
});
});
Login.test(以前的传递版本,但没有Redux存储逻辑)
import React from 'react'
import ReactTestUtils from 'react-dom/test-utils'
import { mount, shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import { missingLogin } from '../../consts/errors'
import Login from './Login'
import Notification from '../common/Notification'
const loginComponent = shallow(<Login />);
const fakeEvent = { preventDefault: () => '' };
describe('<Login /> component', () => {
it('should render', () => {
const tree = toJson(loginComponent);
expect(tree).toMatchSnapshot();
});
it('should render the Notification component if state.error is true', () => {
loginComponent.setState({ error: true });
expect(loginComponent.find(Notification).length).toBe(1);
});
});
1 回答
您的问题是通过将redux存储逻辑混合到测试中,
loginComponent
变量不再表示Login
的实例,而是Provider
包装的实例和Login.
的实例因此,当你这样做
你实际上是在
Provider
实例上调用setState
.我建议测试你用
connect
包装的LoginComponent
与商店状态分开生成LoginContainer
. Redux GitHub repo有a great article on testing connected components,它提供了如何执行此操作的大致概述 .总结一下你需要做什么
分别导出
LoginComponent
和LoginContainer
从容器中单独测试
LoginComponent
,基本上执行您之前在redux存储状态下混合之前的工作测试 .为
LoginContainer
编写单独的测试,您可以在其中测试mapStateToProps
,mapDispatchToProps
和mergeProps
功能 .希望这可以帮助!