简体   繁体   中英

Promise resolves after Mocha times out

I have a worker I'm testing with Mocha, but even though I'm getting the proper response back from promise resolution, Mocha keeps failing the test due to timeout. Crucial fact is that it resolves after Mocha times out.

import chai, { expect } from 'chai';
// Needed otherwise Worker is undefined in the test environment
const Worker = require('webworker-threads').Worker;

describe('WebWorker', () => {
  it('should return correctly', () => {
    return new Promise(res => {
      const dummyWorker = new Worker('./public/js/worker.bundle.js');

      dummyWorker.onmessage = e => {
        console.log('test message'); // 'test message' prints to testing log
        res(e.data);
      };

      dummyWorker.postMessage(['foo', 'bar']);
    })
    .then(workerData => {
      console.log(workerData[0]); // 'foo' prints to testing log
      expect(workerData[0]).to.equal('foo');
    })  
    .catch(err => console.error(err));
  });
});

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

I've tried every some permutations of using done() , using before() hooks, using chai-as-promised, using promises AND Mocha's done, using this.timeout(5000) to increase the timeout, and on and on, but nothing seems to work.

I have narrowed down the problem to the npm package webworker-threads. And what do you know. It's actually an issue that hasn't been resolved yet.

It's only a problem when promises are involved. I thought I tried using done() inside of dummyWorker.onmessage , but I was sadly mistaken. Using done() with webworker-threads works just fine. The problem with using done() however is that any assertion error only ever returns the timeout message. With promises, the error message is much more specific.

Thus, I have switched over to using a different web worker package -- tiny-worker, and it works just fine now.

In the event you want to see the issue with webworker-threads, refer to the simple example below, which reproduces the error without needing an external file:

import { expect } from 'chai';
const Worker = require('webworker-threads').Worker;

describe('web worker', () => {
  it('should resolve', () => {
    const p = new Promise(resolve => {
      const dummyWorker = new Worker(function () {
        this.onmessage = e => {
          self.postMessage('foo');
        };
      });

      dummyWorker.onmessage = e => {
        resolve(e.data);
      };
      dummyWorker.postMessage('foo');
    });

    return p.then(data => {
      console.log(data));
      expect(data).to.equal('bar');
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM