首页 > 解决方案 > 使用 Jest 与 MQTT 进行单元测试

问题描述

我正在使用 Jest 和 MQTT 编写 API 测试用例。我想用我的期望值验证消息的响应值。目前,我无法处理函数 client.on 的响应。请帮我解决一下,非常感谢

测试.ts

    async doTest() {

        client.on('connect', async function () {
            await client.subscribe(topic + '/reply', function (err) {
                 if (!err) {
                   client.publish(topic, JSON.stringify(payload));
                 }
            });
        });

        await client.on('message', async function (topic, message) {
              // message is Buffer
              const res = await JSON.parse(message.toString());
              const { err, response } = res;
              this.result = JSON.stringify(response);
        });
}

    async getResult() {
         return this.result;
}

测试规范.ts

it('should call api', async () => {
    await test.doTest();
    result = await test.getResult();
    console.log(result);
});

标签: unit-testingjestjsmqtt

解决方案


推荐阅读