【问题标题】:Auth middleware not calling stub - NodeJS, sinon身份验证中间件不调用存根 - NodeJS,sinon
【发布时间】:2019-10-06 18:59:57
【问题描述】:

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

  1. Sinon stub being skipped as node express middleware
  2. node express es6 sinon stubbing middleware not working
  3. How to mock middleware in Express to skip authentication for unit test?

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

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 中加载)之后该方法已被模拟,因此我不确定为什么仍在调用原始方法。

我也尝试在模拟之前手动清除缓存,但仍然不起作用。

【问题讨论】:

    标签: javascript node.js unit-testing sinon


    【解决方案1】:

    原来这与 supertest.js 需要 app.js 有关。我现在有 users.spec.js 要求应用程序并将其作为参数传递给超测试方法。现在可以了。仍然不确定为什么

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 好主意,但不幸的是也没有用
      猜你喜欢
      • 2017-03-25
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      相关资源
      最近更新 更多