Giter Club home page Giter Club logo

jest-mock-express's Introduction

@jest-mock/express

A lightweight Jest mock for unit testing Express

Build and Test Coverage Status Known Vulnerabilities GitHub package.json version npm NPM

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

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

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

jest-mock-express's People

Contributors

aboyce avatar bikk-uk avatar dependabot[bot] avatar saramorillon avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jest-mock-express's Issues

get header not working.

Expected Behavior

const req = getMockReq({
  method: 'POST',
  body: {},
  headers: {
    'x-header-name': 'any',
  }
})
const xHeader1 = req.get('x-header-name') // xHeader1 should be 'any'
const xHeader2 = req.header('x-header-name') // xHeader2 should be 'any'

Current

req.get('x-header-name') returns undefined.
req.header('x-header-name') returns undefined.

Reference

Version: 1.4.5

Support For Locals Or Custom Properties

Hi,
In express, you can pass objects between middleware through either adding your custom property to the request object or through the local property provided.

This mock doesn't provide support for either approach.
Would it be possible to add support to one (or both ideally)?

The locals approach would look a bit like this:

const req = getMockReq({locals: {var: "hi there"}})

Needs implement headers on Request.

Hi! I'm using your lib in my TS project, thank you so much, it has been very usefull! But there is a little problem when I try to test headers. As you can see in this link Request, express Request implements IncomingMessage, and they have a property called headers, and I had trouble testing this, I’m sending some screen shots so that you can understand the problem.
Captura de Tela 2020-05-29 às 19 39 18
Captura de Tela 2020-05-29 às 19 39 39
Captura de Tela 2020-05-29 às 19 40 01
Captura de Tela 2020-05-29 às 19 40 10

.status() not chaining

I noticed that when my app had a chained response like so:

response.status(204).send();

the tests would fail because status() is returning undefined in the tests, while really it returns a reference to this enabling it to chain.

To get it to chain properly in my tests I had to implement the following:

// Top of test file
const mockedStatusFunc = jest.fn();
const mockedResponse = getMockRes({ status: mockedStatusFunc });
// In my tests
mockedStatusFunc.mockReturnThis();

I did notice though that it worked just fine if I didn't chain the functions together which is what led me to this conclusion.

// Worked
response.status(204);
response.send();
// Doesn't work
response.status(204).send();

Not working on Simple Function

function getMessage() {
return "Games Resume Backend";
}

this not works:
const showWelcome = (req, res) => {
res.status(200).send({ message: getMessage() })
}

//res.status(200) = works
res.status(200).send .. crashs

Error detail:
Uncaught SyntaxError SyntaxError: Unexpected identifier

type errors in v2.0.0

The following minimal setup does not build without type errors for me.

index.ts

import { getMockReq, getMockRes } from '@jest-mock/express'

getMockReq()

tsconfig.json

{
    "compilerOptions": {
      "allowSyntheticDefaultImports": true,
      "lib": ["es2021"],
      "module": "es2020",
      "moduleResolution": "node",
      "target": "es2021"
    }
}

package.json

{
  "name": "foo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "tsc": "tsc -p ."
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@jest-mock/express": "^1.4.5",
    "@types/express": "^4.17.13",
    "@types/jest": "^28.1.4",
    "jest": "^28.1.2",
    "typescript": "^4.7.4"
  },
  "dependencies": {}
}

results in:

node_modules/@jest-mock/express/dist/src/request/index.d.ts:7:40 - error TS2307: Cannot find module 'src' or its corresponding type declarations.

7 import type { EventEventEmitter } from 'src';
                                         ~~~~~

node_modules/@jest-mock/express/dist/src/request/request.d.ts:6:117 - error TS2304: Cannot find name 'ParsedQs'.

6 export declare const getMockReq: <T extends Request<import("express-serve-static-core").ParamsDictionary, any, any, ParsedQs, Record<string, any>>>(values?: MockRequest) => T;
                                                                                                                      ~~~~~~~~

node_modules/@jest-mock/express/dist/src/response/index.d.ts:7:40 - error TS2307: Cannot find module 'src' or its corresponding type declarations.

7 import type { EventEventEmitter } from 'src';
                                         ~~~~~


Found 3 errors in 3 files.

Errors  Files
     1  node_modules/@jest-mock/express/dist/src/request/index.d.ts:7
     1  node_modules/@jest-mock/express/dist/src/request/request.d.ts:6
     1  node_modules/@jest-mock/express/dist/src/response/index.d.ts:7

Not sure what I'm missing here but the pathes to 'src' really seem off?

The problem does not occur with v1.4.5

Should automatically mock `header`

header has the following type:

    header(name: 'set-cookie'): string[] | undefined;
    header(name: string): string | undefined;

When passing headers to this library, header should be mocked to return the header. It should also be case-insensitive.

Here's the implementation I used:

  header: (header: string) => {
    const headerKeys = Object.keys(headers);

    // Lookup exact header, then case-insensitive
    const headerKey =
      headerKeys.find((headerKey) => headerKey === header) ||
      headerKeys.find((headerKey) => headerKey.toLowerCase() === header.toLowerCase());

    if (!headerKey) {
      return;
    }

    return headers[headerKey];
  },

Implement Writable mocks on Response

Mock implementations for the Express Response have not been implemented deep enough. These need to be implemented to prevent type errors when used.

Express Response hierarchy:

  • express.Response
  • http.ServerResponse
  • http.OutgoingMessage
  • stream.Writable
  • event.EventEmitter

Implement the properties and functions for stream.Writable and event.EventEmitter.

How can I create a mock request with streaming support?

Hello,

I am writing an unit test for multipart form/data content. I would appreciate if there is a way to create a request with streaming so that I can pipe form content. Below is the code.

const form = new FormData(); form.append('meta', {"DxDiagnosis":{"name":"dx mdef name"}}`);
form.append('file', fs.createReadStream('../../files/Dx_Diagnosis - Copy.csv'));

        const req = mockRequest({
            method: 'POST',
            url: '/',
            headers: form.getHeaders(),
            user: {
                sub: '[email protected]',
                role: {
                    name: 'Alerts Engine Admin',
                },
            },
        });`

Implement Readable mocks on Request

Mock implementations for the Express Request have not been implemented deep enough. These need to be implemented to prevent type errors when used.

Express Request hierarchy:

  • express.Request
  • http.IncomingMessage
  • stream.Readable
  • event.EventEmitter

Implement the properties and functions for stream.Readable and event.EventEmitter.

Provide a way to store the data in the response object

currently the only way to test the data is to call

expect(res.send).toHaveBeenCalledWith(...)
expect(res.json).toHaveBeenCalledWith(...)
expect(res.end).toHaveBeenCalledWith(...)

I may be important to store the data in you mock to let it be accessed with
expect(res.data).toBe(...)

It may be done in your mock by saving the args of the send / josn / end

TypeError: res.set is not a function

Running the following code fails when using getMockRes:
res.set('referrer-policy', 'no-referrer');

Also the res.header('referrer-policy', 'no-referrer') alias fails

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.