美文网首页
typescript + mocha 的那些坑

typescript + mocha 的那些坑

作者: 光影魔法师 | 来源:发表于2023-02-21 15:40 被阅读0次

在开发环境,我们通常使用ts-node来直接运行typescript,在这个过程中有一些坑:

1 typescript中的paths

为了简化模块的引用,我们通常在tsconfig中配置路径,


image.png

然而,当我们配置好引用路径后,通过ts-node运行代码时会报找不到此模块的错误,此时就需要安装另一个包:ts-config-paths


image.png

然后在npm 运行命令中添加配置:-r tsconfig-paths/register


image.png

如果是通过Code Runner来执行的,那也需要修改配置:


image.png

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


image.png

2 mocha测试回调方法

我们在开发过程中,常常会用到回调方法callback,而通过mocha要对这类方法进行测试,通常需要调用[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);
      });
    })

以上示例是对一个消息中间件进行测试的代码,步骤如下:

  1. 首先在it声明中增加一个done的参数
  2. 引入sinon模块
  3. 在consumer.subscribe的回调方法中,调用assertionSpy,以便于后面的断言,
  4. 在最后设置一个setTimeout方法,确保断言在回调方法后执行
  5. 在setTimeout方法中执行断言,完成后执行done()方法

相关文章

网友评论

      本文标题:typescript + mocha 的那些坑

      本文链接:https://www.haomeiwen.com/subject/goznkdtx.html