【问题标题】:Unit testing in Typescript with Dependency Injection使用依赖注入在 Typescript 中进行单元测试
【发布时间】:2017-04-25 16:34:09
【问题描述】:

我在单元测试期间遇到了打字稿问题。我尝试像以下代码示例一样对模块进行单元测试:

import {Express} from 'express'

export interface BootClassInterface {
  setup(): Express
}

export class BootClass implements BootClassInterface {

  constructor(private express: () => Express ){

  }

  public test(){
      const app = this.express()
      app.get("/test", (req, res) => {
        res.send("Hello World")
      })

      return app;
  }
}

对于测试建议,我想知道是否调用了 express().get() 以及第一个参数是否为“/test”。在我切换到 typescript 之前,我总是使用模块 sinonJS 来监视或存根功能,以便我可以测试某个依赖项是否正确使用。现在使用 Typescript,我遇到了我在模块中设置的严格类型的问题。举例:

import * as chai from 'chai'
import 'mocha'
import * as sinon from 'sinon'
import * as express from 'express'

import * as Boot from '../../src/Core/Boot'

const assert = chai.assert

suite('[CORE] unit test /Core/Boot.ts', () => {
  let BootClass: Boot.BootClassInterface

  setup(() => {
    const expressApp = () => {
      const app = express()
      app.get = sinon.spy()
      return app
    }

    const Services: Boot.BootServicesInterface = { express: expressApp }
    BootClass = new Boot.BootClass(Services)

  })

  test('Do first test', () => {
    const app = BootClass.setup()
    chai.assert.equal(app.get.called, 1)
  })
})

上面的代码示例导致以下 Typescript 编译错误:

error TS2339: Property 'called' does not exist on type 'ApplicationRequestHandler<Express>'.

我可以看到为什么 typescript 会返回这个错误,而且不知何故它甚至很明显。我什至知道一个可能的解决方案,我接受 Express 作为模块中的任何内容。

但我正在寻找一种更优雅的方式来监视/存根/模拟我的依赖项以进行测试建议,但同时具有严格类型的优势。

【问题讨论】:

  • 另外,在单元测试中,为什么要创建整个 express 应用?

标签: node.js unit-testing typescript dependency-injection sinon


【解决方案1】:

正如您所说,您将Express 指定为BootClassInterface 接口上的返回类型。因此app 将被视为Express,它将查找其属性而不是您的模拟。

您也可以将app 的一个属性转换为any。试试:

 chai.assert.equal((<any>app.get).called, 1)

或者使用Sinon类型定义:

 chai.assert.equal((<SinonSpy>app.get).called, 1)

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多