测试运行并在Login组件中更新状态,然后启用Notification组件(错误消息)
测试失败,预期1,收到0
最初在我添加redux和商店之前,需要在我的测试中使用商店和提供程序逻辑,这Jest / Enzyme个测试正在通过。
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);
});
});
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);
});
});
答案 0 :(得分:1)
您的问题是通过将redux存储逻辑混合到测试中,loginComponent
变量不再代表Login
的实例,而是Provider
包装的实例和{的实例{1}}
因此当你这样做时
Login.
您实际上正在loginComponent.setState({ error: true })
个实例上调用setState
。
我建议您测试Provider
包裹LoginComponent
的{{1}},以便与商店状态分开生成connect
。 Redux GitHub仓库有a great article on testing connected components,其中概述了如何执行此操作。
总结你需要做什么
LoginContainer
和LoginComponent
LoginContainer
,基本上执行您之前在redux存储状态下混合之前的工作测试。LoginComponent
,LoginContainer
和mapStateToProps
功能的mapDispatchToProps
编写单独的测试。希望这有帮助!