0

I have this code:

import * as a from 'a-a';
jest.mock('a-a');

describe('a-a', () => {
    beforeAll(async () => {
        const x = await a.x(1); // Calls the mock
        console.log(x);   // 1
        console.log(a.x.mock) // Undefined
    });
});

The mock function is:

export async function x(data) {
    cache.push(data);

    console.log('HERE'); // this is printed

    return data;
}

The mock of the module is in the __mocks__ directory.

The a.x() calls the mocked function, but a.x.mock is undefined.

How is that possible? Where is the .mock property?

rpadovani
  • 7,101
  • 2
  • 31
  • 50

1 Answers1

0

So, after some investigation I found out that the functions declared in the __mocks__ directory aren't wrapped by jest.fn() by default.

Personally I find the thing a bit confusing.

So you can do both

function x(data) {
    cache.push(data);

    return cache;
}

jest.mock('a-a', () => ({x: x}))

if you do everything in the same file, or

jest.mock('a-a');

and then in the __mocks__/a-a.js file

export const x = jest.fn(async (data) => {
    cache.push(data);

    return cache;
});
rpadovani
  • 7,101
  • 2
  • 31
  • 50