在開(kāi)發(fā)環(huán)境,我們通常使用ts-node來(lái)直接運(yùn)行typescript,在這個(gè)過(guò)程中有一些坑:
1 typescript中的paths
為了簡(jiǎn)化模塊的引用,我們通常在tsconfig中配置路徑,

image.png
然而,當(dāng)我們配置好引用路徑后,通過(guò)ts-node運(yùn)行代碼時(shí)會(huì)報(bào)找不到此模塊的錯(cuò)誤,此時(shí)就需要安裝另一個(gè)包:ts-config-paths

image.png
然后在npm 運(yùn)行命令中添加配置:-r tsconfig-paths/register

image.png
如果是通過(guò)Code Runner來(lái)執(zhí)行的,那也需要修改配置:

image.png
在code-runner.executorMap中找到typescript,添加配置如下:

image.png
2 mocha測(cè)試回調(diào)方法
我們?cè)陂_(kāi)發(fā)過(guò)程中,常常會(huì)用到回調(diào)方法callback,而通過(guò)mocha要對(duì)這類方法進(jìn)行測(cè)試,通常需要調(diào)用[done]方法,或者返回一個(gè)promise。
context('should receive single message test', function () {
it('use `done` for testing', function (done) {
const testTopic = "publisherTest_1"
const testMessage = "order-1"
const assertionSpy = sinon.spy();
consumer.subscribe(testTopic, testMessage, (topic: string, partion: number, message: string | undefined) => {
console.log("receive topic: [%s], message: [%s]", topic, message)
assertionSpy(topic, message)
})
publisher.publish(testTopic, testMessage).then(() => {
console.log("sent topic: [%s], message: [%s]", testTopic, testMessage)
})
setTimeout(function () {
expect(assertionSpy.callCount).to.equal(1)
expect(assertionSpy.args[0][0]).to.equal(testTopic)
expect(assertionSpy.args[0][1]).to.equal(testMessage)
done()
}, 100);
});
})
以上示例是對(duì)一個(gè)消息中間件進(jìn)行測(cè)試的代碼,步驟如下:
- 首先在it聲明中增加一個(gè)done的參數(shù)
- 引入sinon模塊
- 在consumer.subscribe的回調(diào)方法中,調(diào)用assertionSpy,以便于后面的斷言,
- 在最后設(shè)置一個(gè)setTimeout方法,確保斷言在回調(diào)方法后執(zhí)行
- 在setTimeout方法中執(zhí)行斷言,完成后執(zhí)行done()方法