【问题标题】:Sinon Spy not called but original function is called未调用 Sinon Spy 但调用了原始函数
【发布时间】:2018-08-10 09:18:01
【问题描述】:

我的间谍没有被调用,即使我可以看到原始函数中的控制台日志被调用

摩卡测试:

const { expect } = require('chai');
const supertest = require('supertest');
const MyController = require('../../Controllers/MyController');
const sandbox = require('sinon').createSandbox();
const app = require('../../app');

describe('GET /endpoint', () => {
    it('calls handler', (done) => {
        const mySpy = sandbox.spy(MyController, 'handler');

        supertest(app)
            .get('/endpoint')
            .expect(() => {
                expect(mySpy.called).to.be.true;
            })
            .end(done);
    });
});

快递控制器:

function handler(request, response) {
    console.log('I can see this method being called');
    return response.sendStatus(200);
}

module.exports = {
    handler
};

快速路由器:

const router = require('express').Router();
const MyController = require('../Controllers/MyController');

router
    .get('/endpoint', MyController.handler);

module.exports = router;

有什么想法吗?

【问题讨论】:

  • 你的 Mocha 测试第 3 行有一个错字,你用一个 L 写了 Controler
  • 谢谢@PatrickHund - 是我在将代码发布到此处之前简化了代码。虽然它与问题无关
  • 好的,但是路径是否正确?在路由器中,您需要没有任何路径的 MyController,在测试中使用“../”
  • 谢谢,已修复,但再次 - 无关

标签: javascript mocha.js sinon supertest sinon-chai


【解决方案1】:

在这些代码行中:

router
    .get('/endpoint', MyController.handler)

...您正在传递MyController.handler 上定义的实际函数。 router.get() 得到的只是对该函数的引用。
当您稍后在测试中将MyController.handler 包装在一个间谍中时,这不会改变router.get() 对原始函数具有单独引用的事实。

您需要做的是确保路由处理程序始终调用MyController.handler()。把表达式改成这样:

router
    .get('/endpoint', () => MyController.handler())

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 2017-02-12
    • 1970-01-01
    • 2017-04-21
    • 2019-11-24
    • 2017-04-02
    • 2014-11-20
    • 2016-12-23
    • 2014-05-20
    相关资源
    最近更新 更多