What's the best way to unit test an event being emitted in Nodejs?

后端 未结 7 744
孤独总比滥情好
孤独总比滥情好 2021-02-05 02:12

I\'m writing a bunch of mocha tests and I\'d like to test that particular events are emitted. Currently, I\'m doing this:

  it(\'should emit an some_event\', fun         


        
7条回答
  •  耶瑟儿~
    2021-02-05 02:21

    I do it by wrapping the event in a Promise:

    // this function is declared outside all my tests, as a helper
    const waitForEvent = (asynFunc) => {
        return new Promise((resolve, reject) => {
            asyncFunc.on('completed', (result) => {
                resolve(result);
            }
            asyncFunc.on('error', (err) => {
                reject(err);
            }
        });
    });
    
    it('should do something', async function() {
        this.timeout(10000);  // in case of long running process
        try {
            const val = someAsyncFunc();
            await waitForEvent(someAsyncFunc);
            assert.ok(val)
        } catch (e) {
            throw e;
        }
    }
    

提交回复
热议问题