Welcome to the Linux Foundation Forum!

Labs ch-9.1

I have implemented the once method of the eventEmitter to call the event just once and then the listener is removed. However the test is not passing, because the event emitter is undefined in the assertion assert.equal(this, ee). Any hints how to solve it ?

Comments

  • k0dard
    k0dard Posts: 78

    Hello davidwz,

    I don't think that you should touch the assertion...

    Could you post your code please ?

  • krave
    krave Posts: 26

    Perhaps the error is caused by not assigning the return value of new EventEmitter() to the constant ee. You have to keep ee reference to the instance of the event emitter until the assertion finishes.

  • Thats the code:
    'use strict'
    const assert = require('assert')
    const { EventEmitter } = require('events')

    const ee = new EventEmitter()
    ee.once('tick', ()=>console.log('one time called'))
    let count = 0

    setInterval(() => {

    ee.emit('tick');

    }, 100)

    function listener () {

    count++
    setTimeout(() => {
    assert.equal(count, 1)
    assert.equal(this, ee)
    console.log('passed!')
    }, 250)
    }

    listener()

    And thats the error message: AssertionError [ERR_ASSERTION]: undefined == EventEmitter

  • krave
    krave Posts: 26
    edited December 2021

    @davidwz said:
    Thats the code:
    'use strict'
    const assert = require('assert')
    const { EventEmitter } = require('events')

    const ee = new EventEmitter()
    ee.once('tick', ()=>console.log('one time called'))
    let count = 0

    setInterval(() => {

    ee.emit('tick');

    }, 100)

    function listener () {

    count++
    setTimeout(() => {
    assert.equal(count, 1)
    assert.equal(this, ee)
    console.log('passed!')
    }, 250)
    }

    listener()

    And thats the error message: AssertionError [ERR_ASSERTION]: undefined == EventEmitter

    listener should be passed as event handler to event function such as ee.once() or ee.on. Invoking listener function directly as you did in the code - listener() will cause this in the listener function being undefined under strict mode.

    So let's check this assertion:
    asser.equal(this, ee)

    this would be undefined and ee would be the Event Emmitter instance you created before.
    As a result, as mentioned in the error message: undefined == EventEmitter which is not true.

  • krave
    krave Posts: 26

    Here is my code

    'use strict'
    const assert = require('assert')
    const { EventEmitter } = require('events')
    
    const ee = new EventEmitter()
    
    ee.once('tick', listener)
    
    let count = 0
    setInterval(() => {
      ee.emit('tick')
    }, 100)
    
    function listener() {
      count++
      setTimeout(() => {
        assert.equal(count, 1)
        assert.equal(this, ee)
        console.log('passed!')
      }, 250)
    }
    
    
  • Thanks a lot !

  • @krave is correct

Categories

Upcoming Training