首页 > 解决方案 > 身份验证中间件不调用存根 - NodeJS,sinon

问题描述

之前也有人问过类似的问题,我看过并关注了它们,但没有运气:

  1. Sinon 存根作为 node express 中间件被跳过
  2. node express es6 sinon 存根中间件不工作
  3. 如何在 Express 中模拟中间件以跳过单元测试的身份验证?

我从这些得到的一般答案是,在 auth 中间件方法被存根之后app.js,应该需要模块(在我的情况下) 。我已经这样做了,但仍然调用原始中间件:

src/app.js

const authentication = require('./authentication')

...

app.use(['/api/users', '/api/groups'], authentication.ensureAuthenticed])

module.exports = app

src/authentication.js

const { isValidAuth } = require('./lib')

exports.ensureAuthenticated = (req, res, next) => {
    ...
}

__helpers__/supertest.js

// This file just calls endpoints with supertest but this is the only file
// that includes 'app'
const app = require('../../src/app')

module.exports = {
    post: {
        ...
    },
    get: {
        ...
    },
    put: {
        ...
    },
    delete: {
        ...
    }
}

users.spec.js

const authentication = require('../../src/authentication')
const authenticationStubs = require('../__stubs__/authentication')

let supertest
let ensureAuthStub

describe('Users', () => {
    before(() => {
        ensureAuthStub = sinon.stub(authentication, 'ensureAuthenticated').callsFake(authenticationStubs.ensureAuthenticated)
        supertest = require('../__helpers__/supertest')
    })

    // tests

    after(() => {
        ensureAuthStub.restore()
    })
})

__stubs__/authentication.js

exports.ensureAuthenticated = (req, res, next) => {
    ...
}

users.spec.js中,我在方法被模拟后加载supertest.js src/app.js中加载),所以我不确定为什么仍然调用原始方法。

我还尝试在模拟之前手动清除缓存,但仍然无法正常工作。

标签: javascriptnode.jsunit-testingsinon

解决方案


我认为解决方案将使用Rewire代替(或与)Supertest。Rewire 允许您模拟模块的顶级组件。尽管您需要在传递给 Supertest 之前模拟中间件。


推荐阅读