如何使用sinon和mocha模拟节点js中的可配置中间件

问题描述 投票:0回答:1

我有可配置的中间件,可以在其中传递参数,并在此基础上调用下一个函数。

中间件代码:

文件:my-middleware.js

exports.authUser = function (options) {
  return function (req, res, next) {
    // Implement the middleware function based on the options object
    next()
  }
}

var mw = require('./my-middleware.js')

app.use(mw.authUser({ option1: '1', option2: '2' }))

如何使用sinon js模拟中间件?

我已经以这种方式完成,但是它抛出了“ TypeError:next不是一个函数”。

这是我的单元测试代码:

  it("Should return data by id", (done: any) => {

        sandbox.stub(mw, 'authUser')
            .callsFake((req: any, res: any, next: any) => { return next(); });

        server = require('../../index');

        let req = {
            "id": '123'
        }

        chai.request(server)
            .post("/user")
            .send(req)
            .end((request, res) => {

                expect(res.status).to.equal(200);
                expect(res.body.success).to.equal(true);

                done();
            });
    });

您能帮我模拟可配置的中间件吗?预先感谢!

node.js jestjs mocha chai sinon
1个回答
0
投票

通过在标签中指定jestjs,我想您正在使用它。您已经可以使用Jest做很多事情,在这种情况下,您实际上不需要Sinon。 Jest有自己的模拟方式(也有整个模块),类似于jest.mock('./moduleName')

请参阅:https://jestjs.io/docs/en/manual-mocks

© www.soinside.com 2019 - 2024. All rights reserved.