[英]Jest test Fat Arrow in class missing this
我正在Jest中為組件編寫單元測試,而我目前僅在測試功能。
類函數如下:
class Comp extends Component {
fetch = null;
update = async () => {
try {
if(this.fetch)
this.fetch.cancel();
// Do stuff
this.fetch = createFetch();
await this.fetch();
} catch (e) {
console.log('Error in update!!!', e);
}
}
render() {
return(
<div></div>
)
}
}
開玩笑的測試看起來像這樣:
test('Should call fetch.cancel if fetch exists', async () => {
const spy = jest.fn();
const comp = new Comp();
comp.fetch = {cancel: spy};
await comp.update();
expect(spy).toHaveBeenCalledTimes(1);
});
但是我從更新功能得到這個錯誤:
更新錯誤!!! ReferenceError:_this3未定義
誰能幫我這個?
我認為問題不是Jest中的arrow功能,而是您的Comp類中的class屬性。 看一下這個: http : //babeljs.io/docs/plugins/transform-class-properties
編輯:在設置規范模式后可以使用: http : //2ality.com/2017/01/babel-esm-spec-mode.html
在不使用ES6代理的情況下,以這種模式轉譯的模塊盡可能符合規格要求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.