Mock Node External Module Default With Chained Method Using Jest
In our node CLI we have a simple method: 'use strict'; const ora = require('ora'); module.exports = function startSpinner({ textOnStart, color, spinnerType }) { const spinner =
Solution 1:
You've got a couple of options:
You can mock ora
like this:
jest.mock('ora', () => {
const start = jest.fn();
const result = { start };
return jest.fn(() => result);
});
...and then call ora
to get the object it returns (since it always returns the same object) and use that object to access start
:
it('should call ora start', () => {
const result = ora();
expect(result.start).toHaveBeenCalled(); // Success!
});
Or if you want you can attach the start
mock as a property to the ora
mock as an easy way to access it during your tests like this:
const ora = require('ora');
jest.mock('ora', () => {
const start = jest.fn();
const result = { start };
const ora = jest.fn(() => result);
ora.start = start; // attach the start mock to orareturn ora;
});
const startSpinner = require('./startSpinner');
describe('startSpinner', () => {
beforeEach(() => {
startSpinner({});
});
describe('ora', () => {
it('should call ora', () => {
expect(ora).toHaveBeenCalled(); // Success!
});
it('should call ora start', () => {
expect(ora.start).toHaveBeenCalled(); // Success!
});
});
});
Post a Comment for "Mock Node External Module Default With Chained Method Using Jest"