简体   繁体   中英

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.

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

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. Take a look at this: 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

Modules transpiled in this mode conform as closely to the spec as is possible without using ES6 proxies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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