没有以正确的论据调用 Sinon Spy

Sinon Spy not being called with right arguments

背景

我正在尝试通过阅读一本关于该主题的书(巴西语)来学习如何按照 TDD 范式进行 RESTful API:

作者鼓励使用sinon.js together with mocha.js

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

问题

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

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

代码

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. 我的代码有什么问题,为什么不带参数调用响应?

解决方案

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

 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));
    }

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