[英]Mock async action creator in Jest
I am fetching some data from API at componentDidMount
in my react container, this is how the code structure is:我正在我的反应容器中从
componentDidMount
API 获取一些数据,代码结构如下:
export class MainContainer extends Component {
render() {
const { props } = this
const { isFetching, userInfo } = props
return (
isFetching
? <Loading pageName={'Home Page'} />
: <div>
{userInfo
&& <div>
<p>{`Name : ${userInfo.name}`}</p>
<p>{`Email : ${userInfo.email}`}</p>
</div>
}
</div>
)
}
componentDidMount() {
const { props } = this
const { userLogin } = props
// This is an async action creator, came in props by
// `mapDispatchToProps`
userLogin()
}
}
/**
* Maps dispatch and action ceators to render method
* @param {function} dispatch store's dispatch method
* @return {object} action creators in object
*/
function mapDispatchToProps(dispatch) {
// userActionCreators has userLogin method
return bindActionCreators(userActionCreators, dispatch)
}
function mapStateToProps({ user }) {
const { isFetching, error, userInfo } = user
return {
userInfo,
isFetching,
error
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MainContainer)
I recently have started adding unit tests to my code, I am using Jest and Enzyme.我最近开始在我的代码中添加单元测试,我正在使用 Jest 和 Enzyme。 When I run tests I am getting this error:
当我运行测试时,我收到此错误:
TypeError: userLogin is not a function
I know I need to mock userLogin
function, but I am not sure how to pass it on to the container in test file.我知道我需要模拟
userLogin
函数,但我不确定如何将它传递给测试文件中的容器。 This how my test file looks:这是我的测试文件的样子:
import React from 'react'
import renderer from 'react-test-renderer'
import configureStore from 'redux-mock-store'
import { shallow } from 'enzyme'
import { initialState } from '$REDUX/modules/user'
import ConnectedMainContainer, { MainContainer } from './MainContainer'
// Snapshot matching for Main Container
describe('MainContainer Snapshot', () => {
const mockStore = configureStore()
let store, container
beforeEach(() => {
store = mockStore(initialState)
container = shallow(<MainContainer store={store} />)
})
it('Matches the snapshot', () => {
const tree = renderer.create(<MainContainer />).toJSON()
expect(tree).toMatchSnapshot();
})
})
// *************************************************************
Please let me know what am I missing here.请让我知道我在这里缺少什么。
The easiest way would be to just pass it in in the shallow
call.最简单的方法是在
shallow
调用中传递它。
describe('MainContainer Snapshot', () => {
const mockStore = configureStore()
let store, container, userLogin
beforeEach(() => {
userLogin = jest.fn()
store = mockStore(initialState)
container = shallow(<MainContainer store={store} userLogin={userLogin} />)
})
it('Matches the snapshot', () => {
expect(container).toMatchSnapshot();
})
it('logs in the user', () => {
expect(userLogin).toHaveBeenCalled();
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.