我想使用sinon使用ExpressJS和Mongoose为服务的业务逻辑编写测试代码。
我编写了以下测试代码,但findOneService
仅将id作为参数并返回具有该id的文档。
//service_test.js
const sinon = require('sinon');
// Service
const { findOneService } = require('../services/service');
// Schema
const Post = require('../models/mongoose/schemas/post');
describe('findOneService', () => {
let find;
beforeEach(() => {
find = sinon.stub(Post, 'findOne');
});
afterEach(() => {
find.restore();
});
it('should findOne', async () => {
const id = ???;
...?
});
})
//service.js
exports.findOneDocument = async (id) => {
const result = await Post.findOne({_id: id});
if (!result) {
throw new Error('404');
}
return result;
};
如何定义此结果以通过测试代码?
为了测试这种行为,我强烈建议进行集成测试(例如,使用嵌入式/ dockerized MongoDB)。这不仅可以测试服务,还可以测试更多的东西,例如架构,迁移,数据库配置。
但是,如果您只是想试驱动if (!result)...
逻辑,则可以坚持使用sinon。您所缺少的是减去返回值:
it('returns the document if found', async () => {
find.returns('a post');
expect(await findOneService.findOneDocument('id')).toReturn('a post');
});
it('throw error when document does not exist', async () => {
find.returns(null);
expect(() => await findOneService.findOneDocument('non-existent id')).toThrow(Error);
});