在開發(fā)環(huán)境懊悯,我們通常使用ts-node來直接運(yùn)行typescript坎拐,在這個過程中有一些坑:
1 typescript中的paths
為了簡化模塊的引用箩朴,我們通常在tsconfig中配置路徑,
image.png
然而驾孔,當(dāng)我們配置好引用路徑后芍秆,通過ts-node運(yùn)行代碼時會報(bào)找不到此模塊的錯誤惯疙,此時就需要安裝另一個包:ts-config-paths
image.png
然后在npm 運(yùn)行命令中添加配置:-r tsconfig-paths/register
image.png
如果是通過Code Runner來執(zhí)行的,那也需要修改配置:
image.png
在code-runner.executorMap中找到typescript妖啥,添加配置如下:
image.png
2 mocha測試回調(diào)方法
我們在開發(fā)過程中霉颠,常常會用到回調(diào)方法callback,而通過mocha要對這類方法進(jìn)行測試荆虱,通常需要調(diào)用[done]方法蒿偎,或者返回一個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);
});
})
以上示例是對一個消息中間件進(jìn)行測試的代碼怀读,步驟如下:
- 首先在it聲明中增加一個done的參數(shù)
- 引入sinon模塊
- 在consumer.subscribe的回調(diào)方法中诉位,調(diào)用assertionSpy,以便于后面的斷言菜枷,
- 在最后設(shè)置一個setTimeout方法苍糠,確保斷言在回調(diào)方法后執(zhí)行
- 在setTimeout方法中執(zhí)行斷言,完成后執(zhí)行done()方法