Home > Enterprise >  node.js/typescript test: Unit test should return 201 response code
node.js/typescript test: Unit test should return 201 response code

Time:12-29

I have a test 'should return 201 response code' which is failing: Expected: 201 Received: 200

orderController.ts

import { Request, Response } from "express";
import { Orders } from "../models/orders";

const createOrder = async ( req: Request, res: Response) => {
  try {
    const newOrder = await Orders.create(req.body)

    res.status(201).json({
      status: 'success',
      data: {
        order: newOrder,
      }
    })
  } catch (error) {
    res.status(400).json({
      status: 'fail',
      message: error,
    });
  }
}

orderController.test.ts

import { Request, Response } from "express";
import { createOrder } from "../../controllers/orderController";
import { Orders } from "../../models/orders";
import httpMocks from 'node-mocks-http'
import newOrder from '../mock-data/new-order.json'

Orders.create = jest.fn()

let req: Request, res: Response
beforeEach(() => {
  req = httpMocks.createRequest()
  res = httpMocks.createResponse()
})

describe("createOrder", () => {
  it("should have a createOrder function", () => {
    expect(typeof createOrder).toBe("function");
  })
  it("should call Orders.create", () => {
    req.body = newOrder
    createOrder(req, res)
    expect(Orders.create).toBeCalledWith(newOrder)
  })
  it("should return 201 response code", () => {
    req.body = newOrder;
    createOrder(req, res);
    expect(res.statusCode).toBe(201);
  })
})

So in terminal getting:

✕ should return 201 response code (1 ms)

  ● createOrder › should return 201 response code

    expect(received).toBe(expected) // Object.is equality

    Expected: 201
    Received: 200

However if manually create an order in postman shows status: 201 Created.

I have changed even to a more simple orderController.ts like:

const createOrder = async (req: Request, res: Response) => {
  const newOrder = await Orders.create(req.body)
  res.status(201)
}

but getting the same result, cannot pass 'should return 201 response code'. Any ideas?

CodePudding user response:

Just a guess:

  • 200 is the default status code of your mocked response.
  • createOrder is async.
  • when you assert the status code to be 201, createOrder has not been run yet.

Try to await createOrder(...) in your test and see if this helps.

  • Related