Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@jest-mock/express

Package Overview
Dependencies
Maintainers
2
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@jest-mock/express - npm Package Compare versions

Comparing version 1.3.0 to 1.4.0

5

dist/src/request/request.d.ts
import { Request } from 'express';
import type { MockRequest } from './index';
export declare const getMockReq: <T extends Request<import("express-serve-static-core").ParamsDictionary, any, any, import("express-serve-static-core").Query>>(values?: MockRequest) => T;
/**
* Returns a mocked **Express** `Request` with mocked functions and default values.
*/
export declare const getMockReq: <T extends Request<import("express-serve-static-core").ParamsDictionary, any, any, any, Record<string, any>>>(values?: MockRequest) => T;
export default getMockReq;

3

dist/src/request/request.js

@@ -15,2 +15,5 @@ "use strict";

exports.getMockReq = void 0;
/**
* Returns a mocked **Express** `Request` with mocked functions and default values.
*/
const getMockReq = (values = {}) => {

@@ -17,0 +20,0 @@ const { params = {}, query = {}, body = {}, cookies = {}, method = '', protocol = '', secure = false, ip = '', ips = [], subdomains = [], path = '', hostname = '', host = '', fresh = false, stale = false, xhr = false, route = {}, signedCookies = {}, originalUrl = '', url = '', baseUrl = '', accepted = [], get = jest.fn().mockName('get mock default'), header = jest.fn().mockName('header mock default'), accepts = jest.fn().mockName('accepts mock default'), acceptsCharsets = jest.fn().mockName('acceptsCharsets mock default'), acceptsEncodings = jest.fn().mockName('acceptsEncodings mock default'), acceptsLanguages = jest.fn().mockName('acceptsLanguages mock default'), range = jest.fn().mockName('range mock default'), param = jest.fn().mockName('param mock default'), is = jest.fn().mockName('is mock default'), app = {}, res = jest.fn().mockName('res mock default'), next = jest.fn().mockName('next mock default'), aborted = false, httpVersion = '', httpVersionMajor = 0, httpVersionMinor = 0, complete = false, connection = {}, socket = {}, headers = {}, rawHeaders = [], trailers = {}, rawTrailers = [], setTimeout = jest.fn().mockName('setTimeout mock default'), statusCode = 0, statusMessage = '', destroy = jest.fn().mockName('destroy mock default') } = values, extraProvidedValues = __rest(values, ["params", "query", "body", "cookies", "method", "protocol", "secure", "ip", "ips", "subdomains", "path", "hostname", "host", "fresh", "stale", "xhr", "route", "signedCookies", "originalUrl", "url", "baseUrl", "accepted", "get", "header", "accepts", "acceptsCharsets", "acceptsEncodings", "acceptsLanguages", "range", "param", "is", "app", "res", "next", "aborted", "httpVersion", "httpVersionMajor", "httpVersionMinor", "complete", "connection", "socket", "headers", "rawHeaders", "trailers", "rawTrailers", "setTimeout", "statusCode", "statusMessage", "destroy"]);

import { Response, NextFunction } from 'express';
import type { MockResponse } from './index';
/**
* Will return a typed and mocked version of key Express components.
* mockClear() or clearMockRes() will clear all internal jest functions.
* Returns a mocked version of key **Express** components, including:
* - a mocked **Express** `Response`, with mocked functions (chainable) and default values.
* - a mocked `next()` convenience function.
* - `mockClear()` to clear all internal **Jest** functions including `next()`
* - `clearMockRes()` an alias for `mockClear()`
*/
export declare const getMockRes: (values?: MockResponse) => {
res: Response;
export declare const getMockRes: <T extends Response<any, Record<string, any>>>(values?: MockResponse) => {
res: T;
next: NextFunction;

@@ -10,0 +13,0 @@ mockClear: () => void;

@@ -16,4 +16,7 @@ "use strict";

/**
* Will return a typed and mocked version of key Express components.
* mockClear() or clearMockRes() will clear all internal jest functions.
* Returns a mocked version of key **Express** components, including:
* - a mocked **Express** `Response`, with mocked functions (chainable) and default values.
* - a mocked `next()` convenience function.
* - `mockClear()` to clear all internal **Jest** functions including `next()`
* - `clearMockRes()` an alias for `mockClear()`
*/

@@ -20,0 +23,0 @@ const getMockRes = (values = {}) => {

@@ -233,3 +233,3 @@ "use strict";

});
test('allows custom properties, with casting', () => {
test('allows custom properties', () => {
const mockUser = {

@@ -239,16 +239,25 @@ id: '123',

};
// default value is not provided
// default value is not provided, but is typed
const { res: defaultRes } = response_1.default();
const castedDefaultRes = defaultRes;
expect(castedDefaultRes.user).toBeUndefined();
expect(defaultRes.user).toBeUndefined();
// allows setting a custom property
const { res } = response_1.default({ sendDate: true, user: mockUser });
const castedRes = res;
// adds and extra property to the res object
expect(castedRes).toBeDefined();
expect(Object.keys(castedRes).length).toBe(DEFAULT_RES_KEY_LENGTH + 1);
expect(res).toBeDefined();
expect(Object.keys(res).length).toBe(DEFAULT_RES_KEY_LENGTH + 1);
// both properties are available
expect(castedRes.sendDate).toBe(true);
expect(castedRes.user).toBe(mockUser);
expect(res.sendDate).toBe(true);
expect(res.user).toBe(mockUser);
});
test('allows locals to be typed', () => {
const { res } = response_1.default({
locals: {
sessionId: 'abcdef',
isPremiumUser: false,
},
});
expect(res.locals).toBeDefined();
expect(res.locals.sessionId).toBe('abcdef');
expect(res.locals.isPremiumUser).toBe(false);
});
test('the mock next function is provided', () => {

@@ -255,0 +264,0 @@ const { next } = response_1.default();

{
"name": "@jest-mock/express",
"version": "1.3.0",
"version": "1.4.0",
"description": "A lightweight Jest mock for unit testing Express",

@@ -43,14 +43,14 @@ "main": "dist/index.js",

"devDependencies": {
"@types/express": "^4.17.9",
"@types/express": "^4.17.11",
"@types/jest": "^26.0.20",
"@typescript-eslint/eslint-plugin": "^4.12.0",
"@typescript-eslint/parser": "^4.12.0",
"@typescript-eslint/eslint-plugin": "^4.14.1",
"@typescript-eslint/parser": "^4.14.1",
"coveralls": "^3.0.7",
"eslint": "^7.17.0",
"eslint-config-prettier": "^7.1.0",
"eslint": "^7.18.0",
"eslint-config-prettier": "^7.2.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"snyk": "^1.437.3",
"ts-jest": "^26.4.4",
"snyk": "^1.440.1",
"ts-jest": "^26.5.0",
"typescript": "^4.1.3"

@@ -60,2 +60,2 @@ },

"snyk": true
}
}

@@ -30,3 +30,3 @@ # @jest-mock/express

`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` object with mocked functions and default values for properties.
`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.

@@ -37,3 +37,3 @@ ```typescript

To create mock requests with specific values, you can simply provide 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.
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.

@@ -53,5 +53,18 @@ ```typescript

For use with extended Requests, `getMockReq` supports generics.
```typescript
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 provide a `res` object with Jest mock functions. Chaining has been implemented for the applicable functions.
`getMockRes` will return a mocked `res` object with Jest mock functions. Chaining has been implemented for the applicable functions.

@@ -68,9 +81,9 @@ ```typescript

beforeEach(() => {
clearMockRes()
mockClear() // can also use clearMockRes()
})
```
It will also provide a mock `next` function for convenience. That will also be cleared as part of the call to `mockClear`/`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 values, you can simply 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.
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.

@@ -85,6 +98,28 @@ ```typescript

### Example
For use with extended Responses, `getMockRes` supports generics.
A full example could be:
```typescript
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:
```typescript

@@ -91,0 +126,0 @@ // generate a mocked response and next function, with provided values

@@ -247,2 +247,3 @@ // Types

}
interface CustomRequest extends Request {

@@ -249,0 +250,0 @@ user: User

@@ -7,2 +7,5 @@ // Libraries

/**
* Returns a mocked **Express** `Request` with mocked functions and default values.
*/
export const getMockReq = <T extends Request>(values: MockRequest = {}): T => {

@@ -9,0 +12,0 @@ const {

@@ -298,3 +298,3 @@ // Types

test('allows custom properties, with casting', () => {
test('allows custom properties', () => {
interface User {

@@ -304,2 +304,3 @@ id: string

}
interface CustomResponse extends Response {

@@ -314,20 +315,38 @@ user: User

// default value is not provided
const { res: defaultRes } = getMockRes()
const castedDefaultRes = (defaultRes as unknown) as CustomResponse
expect(castedDefaultRes.user).toBeUndefined()
// default value is not provided, but is typed
const { res: defaultRes } = getMockRes<CustomResponse>()
expect(defaultRes.user).toBeUndefined()
// allows setting a custom property
const { res } = getMockRes({ sendDate: true, user: mockUser })
const castedRes = (res as unknown) as CustomResponse
const { res } = getMockRes<CustomResponse>({ sendDate: true, user: mockUser })
// adds and extra property to the res object
expect(castedRes).toBeDefined()
expect(Object.keys(castedRes).length).toBe(DEFAULT_RES_KEY_LENGTH + 1)
expect(res).toBeDefined()
expect(Object.keys(res).length).toBe(DEFAULT_RES_KEY_LENGTH + 1)
// both properties are available
expect(castedRes.sendDate).toBe(true)
expect(castedRes.user).toBe(mockUser)
expect(res.sendDate).toBe(true)
expect(res.user).toBe(mockUser)
})
test('allows locals to be typed', () => {
interface CustomResponse extends Response {
locals: {
sessionId?: string
isPremiumUser?: boolean
}
}
const { res } = getMockRes<CustomResponse>({
locals: {
sessionId: 'abcdef',
isPremiumUser: false,
},
})
expect(res.locals).toBeDefined()
expect(res.locals.sessionId).toBe('abcdef')
expect(res.locals.isPremiumUser).toBe(false)
})
test('the mock next function is provided', () => {

@@ -334,0 +353,0 @@ const { next } = getMockRes()

@@ -8,9 +8,12 @@ // Libraries

/**
* Will return a typed and mocked version of key Express components.
* mockClear() or clearMockRes() will clear all internal jest functions.
* Returns a mocked version of key **Express** components, including:
* - a mocked **Express** `Response`, with mocked functions (chainable) and default values.
* - a mocked `next()` convenience function.
* - `mockClear()` to clear all internal **Jest** functions including `next()`
* - `clearMockRes()` an alias for `mockClear()`
*/
export const getMockRes = (
export const getMockRes = <T extends Response>(
values: MockResponse = {},
): {
res: Response
res: T
next: NextFunction

@@ -169,3 +172,3 @@ mockClear: () => void

return {
res: (response as unknown) as Response,
res: (response as unknown) as T,
next: next as NextFunction,

@@ -172,0 +175,0 @@ mockClear: clearAllMocks,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc