M
M
Meehalkoff2022-01-12 19:50:44
Unit testing
Meehalkoff, 2022-01-12 19:50:44

How to test middleware?

Greetings.

There is such a middleware

import cors, { CorsOptions } from 'cors';
import { HttpConfig } from '../configurations/Http';
import { Middleware } from '../interfaces/express';

const corsOptions: CorsOptions = {
  origin: HttpConfig.DOMAIN,
};

export const CORS: Middleware = cors(corsOptions);


I want to test with jest.

Googled. I came across an article

But I do not quite understand how to use it.

I see the following test situations:
- Access-Control-Allow-Origin is set
- NextFunction is called

Please explain how to test this correctly and how to write the test itself.

I tried like this:
import { Request, Response, NextFunction } from 'express';
import { CORS } from './Cors';

describe('CORS middleware', () => {
  let mockRequest: Partial<Request>;
  let mockResponse: Partial<Response>;
  const nextFunction: NextFunction = jest.fn();

  test('with "CORS" header', async () => {
    mockRequest = {
      headers: {
        host: 'http://localhost:1987',
      },
    };
    mockResponse = {
      setHeader: jest.fn(),
      send: jest.fn(),
    };

    CORS(mockRequest as Request, mockResponse as Response, nextFunction);

    expect(nextFunction).toBeCalledTimes(1);
  });
});

But:
● CORS middleware › with "CORS" header

    TypeError: res argument is required

      at vary (node_modules/vary/index.js:136:11)
      at applyHeaders (node_modules/cors/lib/index.js:151:11)
      at applyHeaders (node_modules/cors/lib/index.js:149:11)
      at applyHeaders (node_modules/cors/lib/index.js:149:11)
      at cors (node_modules/cors/lib/index.js:187:7)
      at node_modules/cors/lib/index.js:224:17
      at originCallback (node_modules/cors/lib/index.js:214:15)
      at node_modules/cors/lib/index.js:219:13
      at optionsCallback (node_modules/cors/lib/index.js:199:9)
      at corsMiddleware (node_modules/cors/lib/index.js:204:7)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question