Easy typed test mocks with Jest and TypeScript
Here’s a quick and simple way to create type-safe test mocks with Jest in TypeScript:
const fooMock: jest.Mocked<IFoo> = {
fooMethod: jest.fn()
}
const testSubject = new ClientClass(fooMock);
This has a few useful properties:
- The type system will enforce that the dependency is the correct type, i.e.
that
ClientClass
is being passed the instance ofIFoo
that it requires. - The type system will enforce that the mock implements the required interface, i.e. that it has stubs for all the required methods.
- The type system can still see that the methods on the mock are
jest.fn
, allowing things likefooMock.fooMethod.mockReturnValue({})
without complaining. - The IntelliJ IDE (e.g. WebStorm or IDEA) can automatically fill in the method
stubs for you once it sees the
jest.Mocked<IFoo>
type annotation.
You can also use TypeScript’s handy Pick
utility type to get more specific
type-safe mocks:
const fooMock: Pick<jest.Mocked<IFoo>, "fooMethod"> = {
fooMethod: jest.fn()
}