簡體   English   中英

帶有依賴注入的Typescript中的單元測試

[英]Unit testing in Typescript with Dependency Injection

我在單元測試期間遇到了打字稿的問題。 我嘗試單元測試模塊,如下面的代碼示例:

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'。 在我切換到打字稿之前,我總是使用模塊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作為模塊中的任何一個。

但我正在尋找一種更優雅的方式來監視/存儲/模擬我的依賴項以進行測試建議,但同時具有嚴格鍵入的優點。

如您所述,您在BootClassInterface接口BootClassInterface Express指定為返回類型。 因此, app將被視為Express ,它將查找其屬性而不是您的模擬。

您也可以將app一個屬性轉換為any屬性。 嘗試:

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

或者使用Sinon類型定義:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM