npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vitest-mock-express

v2.2.0

Published

A lightweight Vitest mock for unit testing Express

Downloads

22,945

Readme

vitest-mock-express

A lightweight Vitest mock for unit testing Express

THIS IS A FORK OF @jest-mock/express ALL CREDITS GOES TO THE ORIGINAL AUTHOR

Getting Started

Installation:

yarn add --dev vitest-mock-express

npm install --save-dev vitest-mock-express

Importing:

import { getMockReq, getMockRes } from 'vitest-mock-express'

Usage

Request - 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)

Response - getMockRes

getMockRes will return a mocked res object with Vitest 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)

Example

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()
})