How to mock a function from the output object of another function

Viewed 54

main.js

import { a } from './a.js';

const { output } = a();

const c = num => num + output.b();

export { c }

a.js

const a = () => ({
    output: { b: () => 5 }, // I want to mock this function
});

export { a }

main.test.js

import { c } from './main.js';

describe('main file', () => {
    test("c function", () => {
        const result = c(4);

        expect(result).toBe(9);
    });
})

How can I mock the output.b function ?

1 Answers

Solution 1

main.test.js:

import { c } from './main.js';

jest.mock('./a.js', () => ({
    a: () => ({
        output: { b: jest.fn(() => 15) }, // adding a mock function
    }),
}));

describe('main file', () => {
    test("c function", () => {
        const result = c(4);
        expect(result).toBe(19);
    });
})

Solution 2

__mocks__/a.js:

const a = () => ({
    output: { b: jest.fn(() => 15) },
});

export { a }

main.test.js:

import { c } from './main.js';

jest.mock('./a.js');

describe('main file', () => {
    test("c function", () => {
        const result = c(4);
        expect(result).toBe(19);
    });
})
Related