'Testing a function that is subscribing to an event

I'm trying to test a function that is subscribing to receive events notifications when a file is changed.

the function is the following:

const ccm2Listener = () => {
  fs.watch(FILE_PATH, (eventType, fileName) => {
    console.log(eventType);
    console.log(fileName);
    // modify the env based on the configurations in the file that changed
  });
};

export default ccm2Listener;

The test:

import ccm2Listener from './ccm2';

it('should update the environment when the ccm2 config file is updated',() => {
  const CCM2_TEST_VALUE = 'Hello World';
  const CCM2_TEST_KEY = 'CCM2_TEST';
  
  // invoking the function we want to test
  ccm2Listener();
  
  // aux function that modifies the file in order to trigger the event
  addEnvToFile(FILE_PATH, { key: CCM2_TEST_KEY, value: CCM2_TEST_VALUE });

  expect(process.env.CCM2_TEST).toBe(CCM2_TEST_VALUE);
});

The problem seems to be that Jest is finishing it's execution before the callback is trigger because I'm getting the following:

Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "rename".

and

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.

Anybody with a clue about how to handle this kind of testing?

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source