【问题标题】:Properly stubbing request/response with Sinon/Mocha使用 Sinon/Mocha 正确地存根请求/响应
【发布时间】:2017-09-30 01:40:54
【问题描述】:

我对后端的单元测试比较陌生,需要一些关于如何对以下内容进行单元测试的指导。我正在使用 Mocha/Should/Sinon。

exports.get = function(req, res) {
   if (req.query.example) {
      return res.status(200).json({ success: true });
   } else {
      return res.status(400).json({error: true});
   } 
}

【问题讨论】:

  • 你使用的是 chai 的“expect”还是“should”语法?
  • 使用 chai 的 should 语法
  • 啊……好的,那我会更新我的答案????
  • 太棒了!绝对是对 sinon 存根的一个很好的入门。试图把我的头缠住!再次感谢!

标签: javascript node.js unit-testing mocha.js sinon


【解决方案1】:

您可以使用 Sinon 的 spy 和 stub 函数来测试您的代码,如下所示:

const { spy, stub } = require('sinon');
const chai = require('chai');
chai.should();

describe('the get function', () => {
    let status,
        json,
        res;
    beforeEach(() => {
        status = stub();
        json = spy();
        res = { json, status };
        status.returns(res);
    });
    describe('if called with a request that has an example query', () => {
        beforeEach(() => get({ query: { example: true } }, res));
        it('calls status with code 200', () =>
            status.calledWith(200).should.be.ok
        );
        it('calls json with success: true', () =>
            json.calledWith({ success: true }).should.be.ok
        );
    });
    describe('if called with a request that doesn\'t have an example query', () => {
        beforeEach(() => get({ query: {} }, res));
        it('calls status with code 400', () =>
            status.calledWith(400).should.be.ok
        );
        it('calls json with error: true', () =>
            json.calledWith({ error: true }).should.be.ok
        );
    });
});

在第一个beforeEach 调用中,我创建了一个名为status 的存根和一个名为json 的间谍。

status 存根用于测试是否使用正确的响应代码调用响应的状态方法。

json spy 用于测试响应的 json 方法是否使用正确的 JSON 代码调用。

请注意,我正在使用 status 的存根,以便能够从任何对 status 方法的调用返回模拟响应,否则链接 (res.status().json()) 将不起作用。

对于json,使用简单的间谍就足够了,因为它位于链的末端。

【讨论】:

    猜你喜欢
    • 2013-12-01
    • 1970-01-01
    • 2021-11-26
    • 2016-02-19
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多