测试承诺超时时用sinon和chai-promise拒绝

时间:2019-05-25 23:49:56

标签: javascript node.js chai sinon

我有一个包装第三方child-process-promise的函数,该第三方本身将spawn包装在promise中。

let spawn = require('child-process-promise').spawn;


run(cmd, args = []) {
    return new Promise(async (resolve, reject) => {
      let command = spawn(cmd, args);
      let childProcess = command.childProcess;
      let result = '';

      childProcess.stdout.on('data', (data) => {
        result += data.toString();
      });

      try {
        const res = await command;
        resolve(result);
      } catch (err) {
        if (err.code && err.code === 'ENOENT') {
          reject(`Command "${cmd}" not found`);
        } else {
          reject('Exec err' + err);
        }
      }
    });
  }

测试解析非常简单,我设法将标准输出数据传递到结果,然后由chai-as-promised使用await expect(shellRun).to.eventually.become('hello world');进行检测

我们的问题是当我们尝试测试方法的catch部分时。

const ERROR = 'someError';

beforeEach(() => {
    sandbox = sinon.createSandbox();

    spawnEvent = new events.EventEmitter();
    spawnEvent.stdout = new events.EventEmitter();

    spawnStub = sandbox.stub();
    spawnStub.returns({ childProcess: spawnEvent });

    spawnStub.withArgs(ERRORED, ARGUMENTS).throws(ERROR));

    shell = proxyquireStrict('../../lib/utils/spawnWrapper', {
      'child-process-promise': {
        spawn: spawnStub
      }
    }
    );
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('when a generic error occurs', () => {
    it('should reject the promise', async () => {
      const shellRun = run(ERRORED, ARGUMENTS);

      await expect(shellRun).to.eventually.be.rejectedWith('Exec err' + ERROR);
    });
  });

通过与ou childProcessPromiseSpawn一起玩,我们设法使spawnStub.withArgs有条件地引发错误。但是遇到超时:

(node:15425) UnhandledPromiseRejectionWarning: Error: someError
(node:15425) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 838)

1 failing

  1) run method
       when a generic error occurs
         should reject the promise:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我们尝试用spawnStub.withArgs(ERRORED, ARGUMENTS).rejects代替throws,但没有成功。将someError的{​​{1}}更改也不起作用。

我们也试图赶上测试水平

new Error('someError')

但是超时仍然发生。

1 个答案:

答案 0 :(得分:0)

这取决于您使用的测试库。每个库都有专用的超时时间。

对于 mocha ,您可以在测试套件中或为唯一测试定义它

https://mochajs.org/#timeouts

相关问题