我正在 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>
)
}
}
Jest 测试如下所示:
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);
});
但是我从更新函数中收到此错误:
Error in update!!! ReferenceError: _this3 is not defined
谁能帮我解决这个问题吗?
最佳答案
我认为问题不是 Jest 中的箭头函数,而是 Comp 类中的类属性。看看这个:http://babeljs.io/docs/plugins/transform-class-properties
编辑:设置规范模式后有效:http://2ality.com/2017/01/babel-esm-spec-mode.html
Modules transpiled in this mode conform as closely to the spec as is possible without using ES6 proxies
关于javascript - 在类里面开 Jest 测试胖箭缺少这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195937/