DEV Community

Tue
Tue

Posted on

Touching more Jest tests

What've I contributed to 2.8

I've had little impact this release. My parser service e2e test works but not perfect, it does test how valid and invalid feeds should be processed when added to the feedQueue but this service doesn't shutdown gracefully. There are a few open handles that hangs Jest:

  const timer = new Promise((resolve, reject) => {
    timerId = setTimeout(() => {
      reject(
        new Error(
          'Unable to connect to Elasticsearch. Use `MOCK_ELASTIC=1` in your `.env` to mock Elasticsearch, or install (see https://github.com/Seneca-CDOT/telescope/blob/master/docs/environment-setup.md)'
        )
      );
    }, DELAY);
  });

  const connectivity = new Promise((resolve) => {
    intervalId = setInterval(async () => {
      try {
        await checkConnection();
        resolve();
      } catch (error) {
        logger.info('Attempting to connect to elasticsearch...');
      }
    }, 500);
  });

  await Promise.race([timer, connectivity]);

  await clearInterval(intervalId);
  clearTimeout(timerId);
Enter fullscreen mode Exit fullscreen mode

The result of Promise.race if all things are well should be a resolved Promise from connectivity, after which is cleared by clearInterval, somehow Jest still detects as open, this could be related to JavaScript event queue. I also tried using unref() following Tim Perry's blog post but to a avail.

  • logger.

Thanks to David's PR turning logger off during test, this problem went away

  • Redis open connections

Some Redis connections are still open after Jest finishes all tests, this was straightforward enough, I tried adding some code that keeps track of all open connections and close them after use and it worked but the logic already exist in Satellite, therefore, I wanted to reuse that code. Thanks to Francesco's work to merge Satellite to Telescope, adding anything to Satellite has become easier.

Modifying Satellite

I opened a PR to modify the stop() from Satellite class to close all database connections (ElasticSearch & Redis). However, I struggled more than I thought.

First of all I changed stop() to return an array of Promises, I used promisify to make server.close() return a Promise but it lost access to this.server in Satellite so I had to bind it with this.server instance.

    const { server } = this;

    const promisifiedClose = server
      ? promisify(server.close.bind(server))
      : () => Promise.resolve();
Enter fullscreen mode Exit fullscreen mode

One of my mistakes was not to pay attention to this piece of code

afterEach(() => {
  service.stop()
});
Enter fullscreen mode Exit fullscreen mode

Yes, the brackets are not needed, I should only return the Promise for Jest to wait.

However, there's still problems with the service not shutting properly after the Satellite's change 😕

Top comments (0)