问题描述
使用 create-react-app
创建一个简单的应用,然后更新我的App.js并添加redux / store。
Created a simple app using create-react-app
then updated my App.js and added redux/store.
class App extends Component {
render() {
return (
<header className="header">
<h1>todos</h1>
</header>
);
}
}
function mapStateToProps(state) {
return {
data: state.data
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
然后尝试使用Enzyme和Jest在App.test.js上测试我的App。
then trying to test my App on App.test.js using Enzyme and Jest.
import React from 'react'
import Enzyme, { mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16';
import App from './App'
Enzyme.configure({ adapter: new Adapter() });
function setup() {
const props = {
addTodo: jest.fn()
}
const enzymeWrapper = mount(<App {...props} />)
return {
props,
enzymeWrapper
}
}
describe('components', () => {
describe('App', () => {
it('should render self and subcomponents', () => {
const { enzymeWrapper } = setup()
expect(enzymeWrapper.find('header')).toBe(true)
})
})
})
但抛出错误:始终违反:在上下文或 Connect(App)。要么将根组件包装在中,要么将存储作为道具传递给 Connect(App)。
but throwing error: Invariant Violation: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(App)".
任何想法?
推荐答案
之所以发生这种情况,是因为您要在没有< Provider>
(
This is happening because you're trying to test the component without a <Provider>
(which would normally make the store available to its sub-components).
在这种情况下,我通常要做的是在没有Redux connect的情况下测试我的组件
绑定。为此,您可以导出 App
组件本身:
What I normally do in this situation is test my component without the Redux connect
binding. To do this, you can export the App
component itself:
导出类App扩展组件//等...
,然后使用解构的赋值语法将其导入测试文件:
and then import that in the test file using the deconstructed assignment syntax:
从'./App'导入{App}
您可以假定(希望...;))Redux和React绑定已经由其创建者进行了正确的测试,并花费您的时间来测试自己的代码。
You can assume (hopefully... ;) ) that Redux and the React bindings have been properly tested by their creators, and spend your time on testing your own code instead.
有关详细信息,请参见
There's a little more information about this in the Redux docs.
这篇关于React,Jest,Enzyme如何通过商店Redux通过测试App.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!