Testing EventEmitter event handlers

huangapple go评论65阅读模式
英文:

Testing EventEmitter event handlers

问题

Here's the translated code portion you requested:

我想测试事件处理测试连接建立后是否已订阅):

```javascript
import * as mqtt from 'mqtt';

export function testEmitter() {

  console.info(`连接到MQTT服务器 ${process.env.MQTT_URL} ...`);

  const client  = mqtt.connect(process.env.MQTT_URL, {
    username: process.env.MQTT_USER,
    password: process.env.MQTT_PASS,
    clientId: process.env.MQTT_CLIENT ?? 'checkmk_zigbee2mqtt',
  });

  client.on('connect', () => {

    console.info(`订阅MQTT主题 ...`);

    client.subscribe(`${process.env.SOME_TOPIC}/#`, { rh: 1, qos: 0 }, () => {});

  });
}

我的jest代码如下:

export class MqttClientMock extends events.EventEmitter {
  subscribe = jest.fn((topic: string, opts: any, callback: ClientSubscribeCallback) => {
    callback(undefined, []);
  });
  publish = jest.fn();
  unsubscribe = jest.fn();
}

describe('emitterTests', () => {

  const mqtt = require('mqtt');

  let client:       MqttClientMock;

  beforeEach(() => {
    client = new MqttClientMock();

    mqtt.connect = jest.fn();
  })

  it('应在连接建立后订阅', (done) => {

    testEmitter();

    expect(mqtt.connect).toBeCalled();

    client.emit('connect', new Error('你做错了'));

    expect(client.subscribe).toBeCalled();

    done();
  })
});

我无法在我所做的任何尝试中创建有效的测试。

上述实现会给出错误消息:TypeError: Cannot read properties of undefined (reading 'on')

其他尝试(例如将testEmitter异步化)告诉我,日志记录'订阅MQTT主题 ...'是在终止后完成的。

我该如何编写一个有效的测试来验证连接后的处理?


请注意,上述代码仅为您提供了翻译后的部分,不包括回答您要翻译的问题。如果您需要进一步的解释或帮助,可以随时提出。

<details>
<summary>英文:</summary>

I want to test handing of an event (test if I have subscribed after a connection has been established):

import * as mqtt from 'mqtt';

export function testEmitter() {

console.info(Connecting to MQTT Server ${process.env.MQTT_URL} ...);

const client = mqtt.connect(process.env.MQTT_URL, {
username: process.env.MQTT_USER,
password: process.env.MQTT_PASS,
clientId: process.env.MQTT_CLIENT ?? 'checkmk_zigbee2mqtt',
});

client.on('connect', () => {

console.info(`Subscribing to MQTT topic ...`);

client.subscribe(`${process.env.SOME_TOPIC}/#`, { rh: 1, qos: 0 }, () =&gt; {});

};



My jest code looks like:

export class MqttClientMock extends events.EventEmitter {
subscribe = jest.fn((topic: string, opts: any, callback: ClientSubscribeCallback) => {
callback(undefined, []);
});
publish = jest.fn();
unsubscribe = jest.fn();
}

describe('emitterTests', () => {

const mqtt = require('mqtt');

let client: MqttClientMock;

beforeEach(() => {
client = new MqttClientMock();

mqtt.connect = jest.fn();

})

it('should subscribe after the connection is established', (done) => {

testEmitter();

expect(mqtt.connect).toBeCalled();

client.emit(&#39;connect&#39;, new Error(&#39;you did wrong&#39;));

expect(client.subscribe).toBeCalled();

done();

})
});


I am not able to create a valid test on any attempt that I made.


Above implementation gives error message: `TypeError: Cannot read properties of undefined (reading &#39;on&#39;)`

Some other attempts (i.e. making testEmitter async) tell me that logging &#39;Subscribing to MQTT topic  ...&#39; is done after termination

How can I write a good test that validates the handling after a connect?






</details>


# 答案1
**得分**: 0

你应该在 `beforeEach` 中模拟 `mqtt.connect` 后,将 `client` 设置为 `mqtt.connect` 的返回值吗?

<details>
<summary>英文:</summary>

Shouldn&#39;t you set `client` as the return value for `mqtt.connect` after mocking it in `beforeEach`?

    beforeEach(() =&gt; {
       client = new MqttClientMock();

       mqtt.connect = jest.fn();
       mqtt.connect.mockReturnValue(client)
    })

</details>



huangapple
  • 本文由 发表于 2023年5月26日 13:44:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定