我正在尝试编写一个简单的测试,以查看是否在下面的componentDidMount
组件中调用了HomePage
:
class HomePage extends Component {
state = {...}
async componentDidMount(){
// a couple of if conditions and an ajax request
}
}
对于测试,我正在尝试以下操作,以查看是否调用了componentDidMount:
describe('<Homepage/>', () => {
let props, store, mockStore, initialState
beforeEach(() => {
props = {
getPoints: jest.fn(),
estimatePoints: jest.fn()
}
initialState = {
homeReducer: {
profile: {}
},
pointsReducer: {
score: {
points: {}
}
}
}
mockStore = configureStore()
store = mockStore(initialState)
})
it('should call the componentDidMount lifecycle method', () => {
const spy = jest.spyOn(HomePage.prototype, 'componentDidMount')
const wrapper = mount(
<Provider store={store}>
<HomePage {...props}/>
</Provider>
)
expect(spy).toHaveBeenCalled()
wrapper.unmount()
})
})
我遇到的错误是Cannot spyOn on a primitive value; undefined given
。我也尝试过使用shallow
和wrapper.instance()
,但都没有运气。在这种情况下,测试componentDidMount
的正确方法是什么?