【发布时间】: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