我有一个react类,它在componentDidMount中有addEventListener,如下所示:
componentDidMount() {
document.addEventListener('readystatechange', () => {
if (document.readyState === 'complete'){
/* Make some api call */
/*Need to test code written here*/
}
});
}
readystatechange事件在更改'document.readyState'时触发,document.readystate是只读的,我该如何模拟此调用?
答案 0 :(得分:0)
我们用来测试函数内部代码的一种解决方法:
let sandbox, addEventListener;
sandbox = sinon.sandbox.create();
addEventListener = sandbox.stub(document, 'addEventListener');
expect(addEventListener.args[0][0]).equal('readystatechange');
addEventListener.args[0][1](); //Call this function that has been registered to this event
expect(api.someFunction).to.have.been.called;