【发布时间】:2019-03-20 09:03:42
【问题描述】:
是否可以使用 Mocha 和 Sinon 在 Express 路由中存根函数?
这是./apps/stuff/controller.js中的实现
import db from '../lib/database';
const getStuff = async (req, res) => {
const results = await db.query(req.id); // I want to stub this
return res.status(200).json({
thingy: results.thingy,
stuff: [
results.foo,
results.bar,
],
});
};
export default {
getStuff,
};
以及它的 Express 路线,在 ./routes.js
import stuff from './apps/stuff/controller';
import express from 'express';
const app = express();
app.route('/stuff')
.get(stuff.getStuff);
所以在测试用例中,我想存根对db.query() 的调用,而是在GET /stuff 请求测试运行期间返回自定义结果。
// ./test/stuff/controller.js
import db from '../../apps/lib/database';
import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../../index';
const { expect } = chai;
chai.use(chaiHttp);
describe('getStuff', () => {
it('gets you stuff', async () => {
// I have tried this, but it results in TypeError: Cannot stub non-existent own property query
// I presume it is creating a new "empty" object instead of stubbing the actual implementation
sandbox.stub(db, 'query').resolves({ thingy: 'bar', stuff: [ 123, 'wadsofasd' ] });
chai.request(server)
.get('/stuff?id=123')
.then(res => {
expect(res).to.have.status(200);
expect(res.body).to.deep.equal({
thingy: 'bar',
stuff: [
123,
'wadsofasd',
]
});
});
});
});
在上述场景中存根/模拟 db.query 调用的正确方法是什么?我已经在网上搜索了几个小时,但没有遇到过类似案例的一个工作版本。
【问题讨论】:
标签: node.js express mocha.js sinon chai