javascript - 在类里面开 Jest 测试胖箭缺少这个

标签 javascript reactjs this jestjs ecmascript-2017

我正在 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/

相关文章:

javascript - jQuery:在按下按钮时运行随机数生成器

javascript - Google reCaptcha 在 React.js 中工作?

javascript - 针对所有类(class),只选择点击的元素

javascript - 关于 jQuery 中 window.unload 的一些(奇怪?)问题

javascript - Dropzone.js 获取文件URL

css - React,从元素中删除类时添加动画?

javascript - 在 React 中将函数组件转换为类组件

javascript - 如何在所需模块内访问 'this'?

javascript - React.js - 实现组件排序

javascript - 调用包含 Promise 的 Async 函数返回未定义