Package Exports
- @jest-mock/express
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@jest-mock/express) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@jest-mock/express
A lightweight Jest mock for unit testing Express
Getting Started
Installation:
yarn add --dev @jest-mock/express
npm install --save-dev @jest-mock/express
Importing:
import { getMockReq, getMockRes } from '@jest-mock/express'Usage
getMockReq
getMockReq is intended to mock the req object as easily as possible. In its simplest form you can call it with no arguments to return a standard req with no values.
const req = getMockReq()To create mock requests with values you can just provide them to the function in any order and all are optional. The advantage of this is that it ensures all of the other properties are not undefined.
// 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 }
})getMockRes
getMockRes will provide a mocked res object with mock functions. Chaining has been implemented for the required 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, clearMockRes } = getMockRes()
beforeEach(() => {
clearMockRes()
})It will also provide a mock next function for convenience, that will also be cleared as part of mockClear/clearMockRes.
const { res, next } = getMockRes()
test('will respond with the entity from the service', async () => {
// generate a mock request
const req = getMockReq({ params: { id: 'abc-def' } })
// provide the mock res and next to check against
await myController.get(req, res, next)
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
id: 'abc-def'
})
)
expect(next).toBeCalled()
})Available Scripts
In the project directory, you can run:
yarn build
Transpiles the TypeScript source to the dist folder.
yarn clean
Clears the dist folder.
yarn test
Runs the tests and produces the coverage output.
yarn test-watch
Runs the tests in watch mode, will not test the dist output folder.
test-watch-all
Runs the tests in watch mode, will test both the TypeScript and generated JavaScript.
yarn lint
Runs the linter over the project.