I'm trying to write unit testing code on my InversifyJS
project. Route testing (using supertest
) is working properly. Then try to write sinon
stub
,spy
testing, but couldn't be successful. My sample code is given below:
DemoRoute
@injectable()
class DemoRoute implements IDemoRoute {
private _demoController:IDemoController;
constructor( @inject(TYPES.IDemoController) demoController:IDemoController ) {
this._demoController = demoController;
}
create(req: Request, res: Response, next: NextFunction) {
return this._demoController.create(req.body)
}
}
Demo.test.ts
import "reflect-metadata";
import * as sinon from "sinon";
const sandbox = sinon.createSandbox();
describe.only("Demo Spec 2", () => {
demoController = container.get<IDemoController>(TYPES.IDemoController);
beforeEach((done) => {
insertStub = sandbox.stub(demoController, 'create');
done();
});
afterEach(() => {
sandbox.restore();
});
it("Should call demo route url", async done => {
demoRoute = container.get<IDemoRoute>(TYPES.IDemoRoute);
const stub = insertStub.returns(Promise.resolve({ body: { name: "test xyz", code: "test abc"} }));
const result = await demoRoute.create({body: demoData.validData}, {send: (params) => params});
expect(stub).to.have.been.called; // throw error
done();
});
}
Error in unit test
UnhandledPromiseRejectionWarning: AssertionError: expected create to have been called at least once, but it was never called
How can I solve this problem? Thanks in advance.