【问题标题】:How to write business logic in a service as sinon in ExpressJS如何在 ExpressJS 中将服务中的业务逻辑编写为 sinon
【发布时间】:2020-03-20 10:34:56
【问题描述】:

我想用 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;
};

如何定义这个结果以通过测试代码?

【问题讨论】:

    标签: express mongoose tdd bdd sinon


    【解决方案1】:

    为了测试这种行为,我强烈建议进行集成测试(例如,使用嵌入式/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);
    });
    
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 2011-02-17
      相关资源
      最近更新 更多