我正在尝试为我的api做一些集成测试。
我的API的结构类似于:
app -> routes -> controllers -> services
因为我已经有单元测试,所以我的想法只是测试所有组件是否以正确的方式连接。
因此,我的想法是与Sinon一起为该服务创建的存根,并且仅使用supertest检查控制器的响应。
[当我运行一个测试时,一切正常。问题是,当我为不同的控制器运行多个单元测试时,存根在第二次运行中不起作用。
我认为是因为该应用程序已经作为模块保存在缓存中,所以sinon无法对服务进行存根。
我的代码的一些示例:
controller.js
const httpStatus = require('http-status');
const { service } = require('../services/croupier');
/**
* Execute lambda tasks for candidates
* @public
*/
exports.task = async (req, res, next) => {
try {
const result = await service({
body: req.body,
authorizer: req.authorizer
});
console.log('res', result);
res.status(httpStatus.OK).json(result);
} catch (error) {
next(error);
}
};
foo.integration.test.js
const request = require('supertest');
const httpStatus = require('http-status');
const sinon = require('sinon');
const mongoose = require('../../../database');
const deleteModule = module => delete require.cache[require.resolve(module)];
const requireUncached = module => {
deleteModule(module);
return require(module);
};
describe('Foo - Integration Test', async () => {
describe('POST /v1/foo', () => {
const fooService = require('../../services/foo');
const stub = sinon.stub(fooService, 'service');
let db;
before(async () => {
db = await mongoose.connect();
});
afterEach(async () => {
sinon.restore();
});
after(async () => {
await db.close();
});
it('the api should response successfully', async () => {
stub.returns({});
const payload = { task: 'task', payload: [{ pathParameters: {}, body: {} }] };
const app = requireUncached('../../../app');
await request(app)
.post('/api/foo')
.send(payload)
.expect(httpStatus.OK);
});
it('the api should response with an error', async () => {
stub.throwsException();
const payload = { task: 'task', payload: [{ pathParameters: {}, body: {} }] };
const app = requireUncached('../../../app');
await request(app)
.post('/api/foo')
.send(payload)
.expect(httpStatus.INTERNAL_SERVER_ERROR);
});
});
});
其他集成测试具有相同的结构。我也尝试使用proxyquire,但没有用。
此外,我也尝试成功删除de app.js的缓存。
有什么想法吗?
上下文:集成测试。
您可以做:
希望这会有所帮助。