我使用Jest和Enzyme编写单元测试。在我的一个React组件中,我渲染了两个不同的redux形式。 它的简化版本如下:
// my_app.js
import React from 'react'
import MyForm from './my_form'
import MyOtherForm from './my_other_form'
class MyApp extends React.PureComponent {
render() {
return (
<div>
<MyForm />
<MyOtherForm />
</div>
)
}
}
// my_form.js
let MyForm = () => <form className='my-form' />
MyForm = reduxForm({ form: 'myForm' })(MyForm)
export default connect(state => state)(MyForm)
// my_other_form.js
let MyOtherForm = () => <form className='my-other-form' />
MyOtherForm = reduxForm({ form: 'myOtherForm' })(MyOtherForm)
export default connect(state => state)(MyOtherForm)
只为控制台日志写一个简单的测试,浅渲染看起来像:
// test.js
import React from 'react'
import { shallow } from 'enzyme'
import MyApp from './my_app'
describe('<MyApp />'), () => {
let wrapper = shallow(<MyApp />)
it('should test something', () => {
console(wrapper.debug())
})
}
会记录如下内容:
<div>
<Connect(ReduxForm) />
<Connect(ReduxForm) />
</div>
我如何断言MyForm和MyOtherForm都被正确呈现?
谢谢!
答案 0 :(得分:0)
您应该使用提供商。 使用Provider时,我使用'mount'而不是'shallow'。 这是一个例子。
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import configureMockStore from 'redux-mock-store';
import LoginForm from '../LoginForm';
const mockStore = configureMockStore();
const dispatch = jest.fn();
const handleSubmit = jest.fn();
const onSubmit = jest.fn();
let store;
const initProps = {
onSubmit,
};
describe('LoginForm', () => {
beforeAll(() => {
store = mockStore({
handleSubmit,
dispatch,
});
dispatch.mockClear();
});
it('renders without exploding', () => {
const wrapper = mount(
<Provider store={store}>
<LoginForm {...initProps} />
</Provider>,
);
expect(wrapper).toHaveLength(1);
expect(wrapper.find('button').prop('disabled')).toBe(true);
});
});
否则,您可以简单地包装表单。
// LoginForm.jsx
const LoginForm = (props) => (
<form>
...
</form>
);
// LoginFormWrapper.jsx
import { reduxForm } from 'redux-form';
import LoginForm from './LoginForm';
export default reduxForm({
form: 'loginForm',
})(LoginForm);
// index.js
export { default } from './LoginFormWrapper';
//test.spec.js
import LoginForm from './LoginForm';
describe('LoginForm', () => {
const wrapper = shallow(<LoginForm />);
expect(wrapper).toHaveLength(1);
});