left click
left click

Reputation: 894

Can I name a `__mocks__` directory?

When I want to mock a file ./a.tsx, I have to create a file __mocks__/a.tsx. But I want to set the filename to like a ./a.mock.tsx.

So I use this pattern in test files.

jest.mock('./a', () => require('./a.mock'));

But That's quite inconvenient, So is there any configuration for this like snapshotResolver or testRegex? Thanks for reading :D

Upvotes: 0

Views: 113

Answers (1)

Juan Rivas
Juan Rivas

Reputation: 603

Jest is not providing any resolver configuration for mock regex patterns at the moment. What you can do instead is creating your own automatic mock classes, as they explain in the documentation.

import AutomaticMock from './a.mock';
jest.mock('./a.mock'); 

beforeEach(() => {
    AutomaticMock.mockClear();
});

it('Create an instance of my AutomaticMock', () => {
    const mock = new AutomaticMock();
    expect(AutomaticMock).toHaveBeenCalledTimes(1);
});

it('Clear any instances of my AutomaticMock', () => {
    expect(AutomaticMock).not.toHaveBeenCalled();
});

Keep in mind that the moment you call jest.mock('./a.mock') this is creating a mock instance of your class that replaces all of its methods with mock functions that always return undefined.

Upvotes: 1

Related Questions