Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JEST throws .finally is not a function

Here is my react component:

import { sendAnalytics } from 'analytics';

class MyComponent extends React.Component {
    myMethod() {
        console.log('do something!');
    }

    render() {
        return (
            <Button 
                onClick={submitAnalytics({name: 'foo'}).finally(this.myMethod())} 
                dataset={{"data-id": "button"}}
            > Send Analytics
            </Button>
            }
        )
    }
}

And my test is like so:

import * as analytics from 'analytics';
jest.mock('analytics');

describe('Analytics', () => {
    it('Should call analytics when button is clicked', () => {
        analytics.submitAnalytics.mockResolvedValue(Promise.resolve(true));
        const tree = ReactTestRenderer.create(<MyComponent />);

        // Actual implementation of following 3 lines is slightly different.
        const button = tree.root.findByProps({"data-id": "button"});
        button.props.onClick();
        expect(analytics.submitAnalytics).toHaveBeenCalled();
    });
});

I tried several different mocking strategies like:

analytics.submitAnalytics.mockImplementation(() => {
    return Promise.resolve(true)
});

Nothing seems to work out. I keep getting the following error:

TypeError: (0 , analytics.submitAnalytics)(...).finally is not a function.

I don't know why. Any help appreciated. Please let me know if you need any more contextual code.

like image 824
darth-coder Avatar asked Jan 17 '19 07:01

darth-coder


3 Answers

Importing @babel/polyfill before the test also solve this problem

import '@babel/polyfill';

// Your tests...
like image 112
Rannie Aguilar Peralta Avatar answered Sep 19 '22 11:09

Rannie Aguilar Peralta


Upgrading my node version from

v8.10.0

to

v10.19.0

Resolved this error.

Looking at the Browser Compatibility chart on MDN it looks like .finally() is not supported in Node until 10.0.0

like image 27
BJax Avatar answered Sep 22 '22 11:09

BJax


import '@babel/polyfill'; worked for me, but is deprecated since babel 7.4.

Instead, import this works fine as well:

import "core-js/stable";
import "regenerator-runtime/runtime";

eventually, I just updated node version (from 8.10.2 to 12.16.1)

like image 28
Séléna Mallet Avatar answered Sep 23 '22 11:09

Séléna Mallet