Skip to content

Instantly share code, notes, and snippets.

@ortense
Created December 1, 2020 17:23
Show Gist options
  • Save ortense/0d6c0eeb989384bd7ddbf7c3df399e19 to your computer and use it in GitHub Desktop.
Save ortense/0d6c0eeb989384bd7ddbf7c3df399e19 to your computer and use it in GitHub Desktop.
How create a unit test a express middleware writed in typescript with jest
import { Application, Request, Response, NextFunction, RequestHandler } from 'express'
describe('How to test a express middleware', () => {
const simpleMiddleware: RequestHandler = (req, res) => {
return res.status(200).json({
message: `App running at http://localhost:${req.app.locals.config.port}`
})
}
const mockApp: Partial<Application> = {
locals: {
config: {
port: 8000
}
}
}
const mockRequest: Partial<Request> = {
app: mockApp as Application
}
const mockResponse: Partial<Response> = {
json: jest.fn().mockImplementation(() => mockResponse),
status: jest.fn().mockImplementation(() => mockResponse),
}
const mockNext = jest.fn() as jest.Mocked<NextFunction>
it('should run correctly', () => {
simpleMiddleware(mockRequest as Request, mockResponse as Response, mockNext)
expect(mockResponse.status).toHaveBeenCalledTimes(1)
expect(mockResponse.status).toHaveBeenCalledWith(200)
expect(mockResponse.json).toHaveBeenCalledTimes(1)
expect(mockResponse.json).toHaveBeenCalledWith({
message: 'App running at http://localhost:8000'
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment