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.
Importing @babel/polyfill
before the test also solve this problem
import '@babel/polyfill';
// Your tests...
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With