How to change the behaviour of a mocked import?

You can mock with a spy and import the mocked module. In your test you set how the mock should behave using mockImplementation: jest.mock(‘the-package-to-mock’, () => ({ methodToMock: jest.fn() })); import { methodToMock } from ‘the-package-to-mock’ it(‘test1’, () => { methodToMock.mockImplementation(() => ‘someValue’) }) it(‘test2’, () => { methodToMock.mockImplementation(() => ‘anotherValue’) })

How to resolve “Cannot use import statement outside a module” from Jest when running tests?

I was having the same failure (also using Babel, Typescript and Jest), it was driving me crazy for hours! Ended up creating a new babel.config.js file specifically for the tests. I had a large .babelrc that wasn’t getting picked up by jest no matter what I did to it. The main app still uses the … Read more

Test process.env with Jest

The way I did it can be found in this Stack Overflow question. It is important to use resetModules before each test and then dynamically import the module inside the test: describe(‘environmental variables’, () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetModules() // Most important – it clears the cache process.env = { …OLD_ENV … Read more

useNavigate() may be used only in the context of a component

This error throws in useNavigate. useInRouterContext will check if the component(which uses useNavigate hook) is a descendant of a <Router>. Here’s the source code to explain why you can’t use useNavigate, useLocation outside of the Router component: useNavigate uses useLocation underly, useLocation will get the location from LocationContext provider. If you want to get the … Read more

Jest + Typescript + Absolute paths (baseUrl) gives error: Cannot find module

I was struggling with the same problem and actually it turns out that a simple change seems to do the trick. I just updated the moduleDirectories field in jest.config.js. Before moduleDirectories: [‘node_modules’] After moduleDirectories: [‘node_modules’, ‘src’] Hope it helps.

Jest: How to mock one specific method of a class

Using jest.spyOn() is the proper Jest way of mocking a single method and leaving the rest be. Actually there are two slightly different approaches to this. 1. Modify the method only in a single object import Person from “./Person”; test(‘Modify only instance’, () => { let person = new Person(‘Lorem’, ‘Ipsum’); let spy = jest.spyOn(person, … Read more