使用摩卡测试异步功能

时间:2019-07-12 13:48:09

标签: javascript async-await mocha

我正在尝试测试以下异步功能。

re = rbind(colMeans(dt[1, ]), colMeans(dt[2, ]), colMeans(dt[3:4, ]), 
      colMeans(dt[5:8, ]), colMeans(dt[9:10, ]))

我的测试代码如下,它在10000 ms之后一直超时。

async taskComplete() {
    this.logger.log('Task Complete');

    try {
      if (fs.existsSync(`${this.repoDir}/.MENLOLAB_EXIT`)) {
        console.log('.MENLOLAB_EXIT Found');

        const exitCode = fs.readFileSync(`${this.repoDir}/.MENLOLAB_EXIT`, 'utf8');
        let msg = '';

        if (exitCode.localeCompare('1')) msg = 'Catchall for general errors';
        else if (exitCode.localeCompare('2')) msg = 'Misuse of shell builtins';
        else if (exitCode.localeCompare('126')) msg = 'Command invoked cannot execute';
        else if (exitCode.localeCompare('127')) msg = '“command not found"';
        else if (exitCode.localeCompare('128')) msg = 'Invalid argument to exit';
        else if (exitCode.localeCompare('128+n')) msg = 'Fatal error signal “n”';
        else if (exitCode.localeCompare('130')) msg = 'Script terminated by Control-C';
        else if (exitCode.localeCompare('255\\*')) msg = 'Exit status out of range';

        await socket.taskExitCode({ jobID: this.taskData.jobID, exitCode, msg });
      } else {
        await socket.taskComplete(this.taskData.jobID);
      }
    } catch (err) {
      this.logger.error('Error attempting to send task complete');
      return this.taskComplete();
    }

    return this.destroyTask();
  }

根据我所见,1) Test MenloLab Runner - Task Class Report TASK.taskComplete() Generate a Report on Task Completion: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/yury.stanev/menlolab/runner/test/tasks-tests.js) 根本没有被调用。造成这种行为的原因是什么?

taskComplete()

1 个答案:

答案 0 :(得分:0)

不得不将函数调用修改为await this.task.taskComplete(),这很奇怪。最终的测试代码如下。

describe('Report', () => {
    describe('TASK.taskComplete()', () => {
      it('Generate a Report on Task Completion', async () => {
        try {
          const task = new TASK(taskData, () => {});
          await this.task.taskComplete();
          if (fs.existsSync(`${this.repoDir}/.MENLOLAB_EXIT`)) {
            expect(`${this.repoDir}/.MENLOLAB_EXIT`).to.be.a.file().and.not.empty;
          } else {
            expect(task.destroyTask()).to.be.true;
          }
        } catch (err) {
          expect(err).to.not.be.undefined;
        }
      });
    });
  });