简体   繁体   English

开玩笑地在课堂上测试Fat Arrow

[英]Jest test Fat Arrow in class missing this

I'm writing unit tests for a Component in Jest and I'm currently just testing functionality. 我正在Jest中为组件编写单元测试,而我目前仅在测试功能。

The class function is as followed: 类函数如下:

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>
        )
    }
}

The jest test looks like this: 开玩笑的测试看起来像这样:

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);
});

But I'm getting this error from the update function: 但是我从更新功能得到这个错误:

Error in update!!! 更新错误!!! ReferenceError: _this3 is not defined ReferenceError:_this3未定义

Can anyone help me with this? 谁能帮我这个?

I assume the problem is not the arrow function in Jest, but the class property in your Comp class. 我认为问题不是Jest中的arrow功能,而是您的Comp类中的class属性。 Take a look at this: http://babeljs.io/docs/plugins/transform-class-properties 看一下这个: http : //babeljs.io/docs/plugins/transform-class-properties

Edit: It worked after setting the spec mode: http://2ality.com/2017/01/babel-esm-spec-mode.html 编辑:在设置规范模式后可以使用: 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 在不使用ES6代理的情况下,以这种模式转译的模块尽可能符合规格要求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM