Search code examples
javascriptmocha.jschaisinonsinon-chai

Sinon Stub is Undefined


Can't make this test to work. Always returns:

TypeError: Cannot read property 'be' of undefined

package.json (devDependencies)

"chai": "^4.3.6",
"chai-as-promised": "^7.1.1",
"mocha": "^10.0.0",
"sinon": "^9.0.1",
"sinon-chai": "^3.7.0",
"supertest": "^4.0.2",
"ts-node": "^10.7.0",

.mocharc

{
  "diff": true,
  "extension": ["ts"],
  "package": "./package.json",
  "reporter": "spec",
  "slow": "75",
  "timeout": "2000",
  "ui": "bdd",
  "watch-files": ["test/*.ts"],
  "require": ["ts-node/register"]
}

mytest.spec.ts

import * as request from 'supertest';
import * as sinon from 'sinon';
import * as express from 'express';
import * as appSetup from '../src/app';


describe('Requests handler', () => {
  let app: express.Application;
  before(async function (): Promise<void> {
    app = await appSetup.init();
  });

  describe('Success', () => {
    it('Should success', async () => {
      const payload = { name: 'name', age: 20 };
      const resp = await request(app)
        .post('/my/url')
        .set('Content-Type', 'application/json');
        .send(payload)

      resp.status.should.be.equal(201); // Here is undefined.
    });
  });
});

BUT, If I use chai expect it works;

import { expect } from 'chai';

expect(resp.status).to.be.equal(201); // WORKS

Why am I getting this error when using sinon?


Solution

  • You need to call chai.should() so that it will extend Object.prototype. See assertion styles

    import chai from 'chai';
    chai.should();