我试图通过supertest库请求在快速路由器中的某个路由上调用存根函数。我看到函数foo被正确调用,不幸的是它没有被我在测试中写的存根函数所取代。代码是用ES6编写的,我使用babel-register和babel-polyfill来使其工作。
我使用测试脚本
./node_modules/mocha/bin/mocha server --timeout 10000 --compilers js:babel-register --require babel-polyfill --recursive
router.js
import {foo} from '../controller';
const router = new Router();
router.route(ROUTE).post(foo);
controller.js
export function foo(req, res) {
res.status(200).send({
ok: 'ok'
});
}
test.js
import request from 'supertest';
import sinon from 'sinon';
import {app} from 'app';
import * as controller from 'controller';
const agent = request.agent(app);
describe('Admin routes tests', () => {
it('Tests login admin route', async () => {
const bar = () => {
console.log('bar');
};
sinon.stub(controller, 'foo', bar);
const req = await agent
.post(ROUTE)
.set('Accept', 'application/json');
console.log(stub.calledOnce); // false
});
});
非常感谢任何帮助。
答案 0 :(得分:1)
这是解决方案:
app.js
:
import express from "express";
import * as controller from "./controller";
const app = express();
app.post("/foo", controller.foo);
export { app };
controller.js
:
export function foo(req, res) {
res.status(200).send({ ok: "ok" });
}
test.js
:
import request from "supertest";
import sinon from "sinon";
import * as controller from "./controller";
import { expect } from "chai";
describe("Admin routes tests", () => {
it("Tests login admin route", (done) => {
const bar = () => {
console.log("bar");
};
const fooStub = sinon.stub(controller, "foo").callsFake(bar);
const { app } = require("./app");
const agent = request.agent(app);
agent
.post("/foo")
.set("Accept", "application/json")
.timeout(1000)
.end((err, res) => {
sinon.assert.calledOnce(fooStub);
expect(res).to.be.undefined;
expect(err).to.be.an.instanceof(Error);
done();
});
});
});
由于对foo
控制器进行了存根处理,并且其返回值为undefined
。对于supertest
,没有响应,例如res.send()
,服务器将挂起直到mocha测试超时,这将导致测试失败。
.mocharc.yml
:
recursive: true
require: ts-node/register
timeout: 2000
diff: true
inline-diffs: true
我们添加.timeout(1000)
来进行超级测试,因为我们知道它会超时(您将foo
控制器与bar
相乘)。并且,对此超时错误进行断言。
具有覆盖率报告的集成测试结果:
Admin routes tests
bar
✓ Tests login admin route (1341ms)
1 passing (1s)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 95.65 | 100 | 80 | 95.65 | |
app.ts | 100 | 100 | 100 | 100 | |
controller.ts | 50 | 100 | 0 | 50 | 2 |
test.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/41600031