[英]I want to test whether a method is called within the lifecycle method componentDidMount, but I am getting an error
I have a lifecycle method, componentDidMount
that is calling a function, setDateOnMount
which will be a spy within it.我有一个生命周期方法,
componentDidMount
,它正在调用一个函数, setDateOnMount
,它将成为其中的一个间谍。 I am using jest and enzyme to test whether setDateOnMount
runs or not, and I am getting an error that it is not called.我正在使用 jest 和酶来测试
setDateOnMount
是否运行,并且我收到一个错误,它没有被调用。
I have seen posts with the wrapper being called with mount
rather than shallow
, but I can't use mount because I am using the react-dates package, and it is conflicting with mount, where I cannot run it.我见过使用
mount
而不是shallow
调用包装器的帖子,但我不能使用 mount 因为我使用的是 react-dates 包,并且它与 mount 冲突,我无法运行它。
Here is my test:这是我的测试:
test('componentDidMount should be called with setDateOnMount', () => {
const setDateOnMount = jest.fn()
const location = {
state: undefined
}
const componentDidMount = jest.spyOn(MealSummary.prototype, 'componentDidMount')
const wrapper = shallow(<MealSummary meals={meals} location={location} setDateOnMount={setDateOnMount} />)
expect(componentDidMount).toHaveBeenCalledTimes(1)
expect(setDateOnMount).toHaveBeenCalledTimes(1) //errors here that it is not called
})
The partial component I am testing is here:我正在测试的部分组件在这里:
.
.
componentDidMount() {
this.setDateOnMount()
}
.
.
...
How can I get it to work?我怎样才能让它工作?
To test if setDateOnMount
is called or not, you can mock or spy on it:要测试是否
setDateOnMount
,您可以模拟或监视它:
test('componentDidMount should be called with setDateOnMount', () => {
const setDateOnMount = jest.spyOn(MealSummary.prototype, 'setDateOnMount') // spy
const wrapper = shallow(<MealSummary meals={[]} location={{state: undefined}} />) // create
expect(setDateOnMount).toHaveBeenCalledTimes(1) // test
})
test('componentDidMount should be called with setDateOnMount', () => {
const setDateOnMount = MealSummary.prototype.setDateOnMount = jest.fn() // mock
const wrapper = shallow(<MealSummary meals={[]} location={{state: undefined}} />) // create
expect(setDateOnMount).toHaveBeenCalledTimes(1) // test
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.