dz210
dz210

Reputation: 768

Jest: How to ignore __mocks__ folder for specific test and instead use a mock I define in the test file?

I have a __mocks__ folder that mocks out a node module. This works for most of my tests, but in one particular test I need a custom mock. I need my unit-tested code to ignore the mock in the __mocks__ folder, and use a specific mock that I define in the test file.

I tried using jest.unmock(), however this prevents me from defining specific mocks in my unit test (thing.test.js). If I then add some mocks or modify the module I'm mocking, the changes don't get added to the code I'm testing (thing.js).

Example:

Upvotes: 2

Views: 2442

Answers (1)

Steven Scott
Steven Scott

Reputation: 11250

I am using Typescript, but the same approach applies. I create my normal test files (thing.spec.ts) which tests the code. In our code base, we do basic tests in this file, and would use it to test non-mocked functions, and simply spyOn() calls.

We then create a separate test file (thing.mock.spec.ts) where the 'mock' indicates that the tests in the this file, are going to be using the __mock__ directory class instead. The naming is just our internal standard to be clear of what we are using.

In the thing.mock.spec.ts we do the mock of the complete class as you are doing in your test. This test file only tests functions that require the mock data, since the main tests have been done independently in the thing.spec.ts.

This would then have:

__mocks__/AWS.js
thing.js
thing.test.js
thing.mock.test.js

This way, when looking at just the file names, you get a sense of what is being used during the testing.

Upvotes: 1

Related Questions