[英]I want to test whether a method is called within the lifecycle method componentDidMount, but I am getting an error
我有一个生命周期方法, componentDidMount
,它正在调用一个函数, setDateOnMount
,它将成为其中的一个间谍。 我正在使用 jest 和酶来测试setDateOnMount
是否运行,并且我收到一个错误,它没有被调用。
我见过使用mount
而不是shallow
调用包装器的帖子,但我不能使用 mount 因为我使用的是 react-dates 包,并且它与 mount 冲突,我无法运行它。
这是我的测试:
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
})
我正在测试的部分组件在这里:
.
.
componentDidMount() {
this.setDateOnMount()
}
.
.
...
我怎样才能让它工作?
要测试是否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.