Mocking Classes with Jest and Typescript
Cross posted on dev.to.
TLDR
GetANumber.test.ts mocks a class, and further customizes a class method on that mocked class for a single test.
Improvements
- config object should have only getters, that way you can mock process.env inbetween tests
- they’ll be sourced every time, not pulled from process.env and held onto
Purpose
It was surprisingly hard to find a recently written article about the fastest way to setup Jest with some simple class mocks in Typescript. The following example demonstrates mocking a class and modifying methods of that mocked class within a single test.
Libraries like jest-ts-auto-mock are not used, cause I was unable to find a way to get them to work. Could have just been using them wrong but who knows.
I used the following methods to mock classes in an Express app while coding in test driven development.
Explanation
Comments are all over in this Example Repo, but some highlights are:
jest.mock
ends up at the top of the file when it’s transpiled. Even if you put it under other things, it gets pulled to the top.
1 | /////////////////// |
- The examples mock a class that’s a default export. Named exports can also be mocked with some modifications.
jest.mock('{path_to_custom_class}')
will replace that paths default export in the runtime with the defined mock in__mocks__
dir defined at the same level.- If you’d like to modify a mock / assert things that happened to a mock, you need to import them from the “real” class.
- Never manually import from
__mocks__
, get the exports of__mocks__
“through” a normal import.
- Never manually import from
1 | import * as MockNumberGen from "./__mocks__/NumberGen"; |
The full test is available here