使用bind测试类中的回调(this)

时间:2016-08-31 13:31:02

标签: javascript node.js unit-testing mocha chai

我正在构建基于TDD的应用程序,当我尝试将函数调用绑定到另一个函数中时,我在处理测试时遇到了麻烦:

/**
   * Loads the client trusted strategy from passport
   */
  apply () {
    passport.use(this.name, new passportStrategy.Strategy(this.callback.bind(this)))
  }

我需要测试使用对象回调方法调用的passportStrategy.Strategy。

这是我的测试:

it('should call the passport.use method with clientTrusted value and a new Passport strategy object', () => {
      const spy = chai.spy()
      const ClientTrustedProxied = proxyquire('./../../../app/business/strategy/ClientTrusted', {passport: {use: spy}})
      const clientTrusted = new ClientTrustedProxied(null, Constants.STRATEGY_CLIENT_TRUSTED)
      clientTrusted.apply()
      expect(spy).to.have.been.called.with(Constants.STRATEGY_CLIENT_TRUSTED, new Strategy(clientTrusted.callback))
    })

事实是clientTrusted.callback与this.callback.bind(this)不同(显然)所以我无法测试两个元素的相等性。

但是如果我删除bind(),测试就会传递绿色,但我的应用程序不再起作用了(超级js范围)。

我需要一个解决方案,或者至少是一些帮助,才能使测试成为绿色。

注意:测试中的策略对象如下:

import { Strategy } from 'passport-oauth2-public-client'

或在课堂上(由于名称冲突):

import * as passportStrategy from 'passport-oauth2-public-client'

谢谢你的帮助

0 个答案:

没有答案