Home > OS >  How to test next parameter in controller using mocha and chai
How to test next parameter in controller using mocha and chai

Time:08-04

I've got a controller which I'm using the 'next' parameter, and I have no idea how to include it into the test. I've done request and response, everything is ok, but when I use the next, I've got the error asking for the 3rd argument. How to test 'next' in this case?

error

Expected 3 arguments, but got 2.ts(2554)
car.controller.ts(20, 5): An argument for 'next' was not provided.

controller test

describe('Cars Controller Tests', () => {
  const carModel = new CarModel();
  const carService = new CarService(carModel);
  const carController = new CarController(carService);
  const req = {} as Request;
  const res = {} as Response;

  before(async () => {
    sinon.stub(carService, 'create').resolves(mock.carMockWithId);
    res.status = sinon.stub().returns(res);
    res.json = sinon.stub().returns(res);
  });

  after(()=>{
    sinon.restore();
  })

  it('1 - CREATE runs successfully', async () => {
    req.body = mock.carMock;
    await carController.create(req, res);
    expect((res.status as unknown as sinon.SinonStub).calledWith(201)).to.be.true;
    expect((res.json as sinon.SinonStub).calledWith(mock.carMockWithId)).to.be.true;
  });
});

CodePudding user response:

I just got from an article I found:

declare Next then test as usual:

const req = {} as Request;
const res = {} as Response;
const next = {} as NextFunction;
....
await carController.create(req, res, next);
  • Related