【问题标题】:Sinon Spy not being called with right argumentsSinon Spy 没有被正确的论据调用
【发布时间】:2017-09-24 02:14:24
【问题描述】:

背景

我正在尝试通过阅读有关该主题的书籍(巴西文)来学习如何按照 TDD 范式创建 RESTful API:

作者鼓励sinon.jsmocha.js一起使用。

我接近尾声了,但我的gnomeController 的测试未能通过。

问题

问题是我使用 sinon 来断言我正在使用给定的响应对象调用gnomeControllerget 方法,这实际上是一个间谍。

这个间谍是为了确保我调用带有“错误”的响应方法,但似乎我在调用响应时没有任何参数,这非常令人困惑。

代码

gnomeController.js

module.exports = aGnomeModel => {

    let Gnome = aGnomeModel;

    function get(req, res){
        return Gnome.find({})
            .then(gnomes => res.send(gnomes))
            .catch(err => res.status(400).send(err));
    }

    return Object.freeze({
        get
    });
};

gnomeTest.js

const sinon = require("sinon");
const gnomesControllerFactory = require("gnomesController.js");
const Gnome = require("gnomeModel.js");

describe("Controllers: Gnomes", () => {

    describe("get() gnomes", () => {

        it("should return 400 when an error occurs", () => {
            const request = {};
            const response = {
                send: sinon.spy(),
                status: sinon.stub()
            };

            response.status.withArgs(400).returns(response);
            Gnome.find = sinon.stub();
            Gnome.find.withArgs({}).rejects("Error");

            const gnomesController = gnomesControllerFactory(Gnome);

            return gnomesController.get(request, response)
                .then(arg => {
                    console.log(arg);
                    sinon.assert.calledWith(response.send, "Error");
                });
        });
    });

});

问题

我正在使用这两个库的最新版本。

  1. 我的代码有什么问题,为什么在没有参数的情况下调用响应?

【问题讨论】:

    标签: javascript node.js tdd mocha.js sinon


    【解决方案1】:

    解决方案

    经过多次调试,我发现解决方案是替换:

     function get(req, res){
            return Gnome.find({})
                .then(gnomes => res.send(gnomes))
                .catch(err => res.status(400).send(err));
        }
    

    与:

     function get(req, res){
            return Gnome.find({})
                .then(gnomes => res.send(gnomes))
                .catch(err => res.status(400).send(err.name));
        }
    

    这在书中没有解释。有点希望我能提供更多反馈,但到目前为止就是这样。

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2021-11-16
      • 2017-01-07
      • 2014-05-20
      • 1970-01-01
      相关资源
      最近更新 更多