I’ve been trying for quite a while to create a mock implementation of Ora and then use jest to test that it calls several functions from it like start, stop, info. Also, I’m doing this with ES6.
Module:
import ora from 'ora'
export async function myModule({
const spinner = ora({
text: "this is a test",
}).start();
spinner.info('continue the test)
spinner.stop()
});
Test:
import { beforeEach, describe, jest } from '@jest/globals'
jest.unstable_mockModule('ora', () => ({
default: jest.fn(() => ({
start: jest.fn().mockReturnThis(),
info: jest.fn().mockReturnThis(),
succeed: jest.fn().mockReturnThis(),
fail: jest.fn().mockReturnThis(),
stop: jest.fn().mockReturnThis(),
})),
}));
const { default: ora } = await import('ora');
const { myModule } = await import('./myModule.js')
describe('my_test', () => {
beforeEach(() => {
jest.clearAllMocks();
});
const test = await myModule()
expect(ora.start).toHaveBeenCalled();
I was eventually able to copy what someone else had done and it did work with this code below, but I don’t understand WHY this works. I would like to understand why this works so that I can apply that information to other modules that I may need to mock, and I want to do it with as little code as necessary.
import { beforeEach, describe, jest } from '@jest/globals'
const mockOra = {
fail: jest.fn(),
succeed: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
stop: jest.fn(),
};
mockOra.start = jest.fn(() => mockOra);
jest.mock('ora', () => jest.fn(() => mockOra));
const { default: ora } = await import('ora');
const { myModule } = await import('./myModule.js')
describe('my_test', () => {
beforeEach(() => {
jest.clearAllMocks();
});
const test = await myModule()
expect(ora.start).toHaveBeenCalled();