A lightweight Jest mock for unit testing Express
The npm package "@jest-mock/express" is an essential tool for developers who use Jest to test Express applications. This lightweight mock library simplifies the process of creating mock Express objects like request, response, and next functions, enabling a more efficient and streamlined unit testing environment. By using "@jest-mock/express," developers can easily simulate Express middleware and route handlers without needing to set up and tear down actual Express servers. This not only speeds up the testing process but also ensures tests are focused and isolated, leading to more reliable and maintainable code.
To start using this powerful testing library in your project, simply run the command `npm install @jest-mock/express`. This command installs the package into your Node.js project, adding it to your package.json dependencies. Once installed, "@jest-mock/express" allows you to mock Express APIs in your Jest tests, which can significantly reduce the complexity of your test setups and improve test execution speed. The ease of setup provided by this command makes it accessible even to developers new to testing with Jest and Express, thereby fostering a more test-driven development culture.
One of the key benefits of using "@jest-mock/express" is its ability to support various testing scenarios that involve HTTP requests and responses. The package provides methods to mock specific Express functionalities, such as chaining middleware, handling error scenarios, and testing route-specific logic. This flexibility ensures that developers can cover a wide range of use cases in their tests, from simple unit tests to more complex integration tests involving multiple middleware and routes. Moreover, "@jest-mock/express" is maintained actively, with updates that keep pace with new versions of Jest and Express, ensuring that it remains a reliable tool in a developer’s testing arsenal.
Core dependencies of this npm package and its dev dependencies.
@types/express, @snyk/protect, @types/jest, @typescript-eslint/eslint-plugin, @typescript-eslint/parser, eslint, eslint-config-prettier, eslint-plugin-prettier, jest, prettier, ts-jest, typescript
A README file for the @jest-mock/express code repository. View Code
A lightweight Jest mock for unit testing Express
Installation:
yarn add --dev @jest-mock/express
npm install --save-dev @jest-mock/express
Importing:
import { getMockReq, getMockRes } from '@jest-mock/express'
getMockReq
getMockReq
is intended to mock the req
object as quickly as possible. In its simplest form, you can call it with no arguments to return a standard req
object with mocked functions and default values for properties.
const req = getMockReq()
To create a mock req
with provided values, you can pass them to the function in any order, with all being optional. The advantage of this is that it ensures the other properties are not undefined
. Loose type definitions for standard properties are provided, custom properties ([key: string]: any
) will be passed through to the returned req
object.
// an example GET request to retrieve an entity
const req = getMockReq({ params: { id: '123' } })
// an example PUT request to update a person
const req = getMockReq({
params: { id: 564 },
body: { firstname: 'James', lastname: 'Smith', age: 34 },
})
For use with extended Requests, getMockReq
supports generics.
interface AuthenticatedRequest extends Request {
user: User
}
const req = getMockReq<AuthenticatedRequest>({ user: mockUser })
// req.user is typed
expect(req.user).toBe(mockUser)
getMockRes
getMockRes
will return a mocked res
object with Jest mock functions. Chaining has been implemented for the applicable functions.
const { res, next, clearMockRes } = getMockRes()
All of the returned mock functions can be cleared with a single call to mockClear
. An alias is also provided called clearMockRes
.
const { res, next, mockClear } = getMockRes()
beforeEach(() => {
mockClear() // can also use clearMockRes()
})
It will also return a mock next
function for convenience. next
will also be cleared as part of the call to mockClear
/clearMockRes
.
To create mock responses with provided values, you can provide them to the function in any order, with all being optional. Loose type definitions for standard properties are provided, custom properties ([key: string]: any
) will be passed through to the returned res
object.
const { res, next, clearMockRes } = getMockRes({
locals: {
user: getLoggedInUser(),
},
})
For use with extended Responses, getMockRes
supports generics.
interface CustomResponse extends Response {
locals: {
sessionId?: string
isPremiumUser?: boolean
}
}
const { res } = getMockRes<CustomResponse>({
locals: {
sessionId: 'abcdef',
isPremiumUser: false,
},
})
// res.locals is typed
expect(res.locals.sessionId).toBe('abcdef')
expect(res.locals.isPremiumUser).toBe(false)
A full example to test a controller could be:
// generate a mocked response and next function, with provided values
const { res, next } = getMockRes({
locals: {
isPremiumUser: true,
},
})
test('will respond with the entity from the service', async () => {
// generate a mock request with params
const req = getMockReq({ params: { id: 'abc-def' } })
// provide the mock req, res, and next to assert
await myController.getEntity(req, res, next)
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
id: 'abc-def',
}),
)
expect(next).toBeCalled()
})