异步回调中的Mocha测试 [英] Mocha testing inside async callbacks

查看:163
本文介绍了异步回调中的Mocha测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经简化了示例,以便能够很好地解释它.我有一个要迭代的数组.对于数组的每个元素,我想使用async/await函数执行测试,因此我有以下代码:

I have simplified the example to be able to explain it well. I have an array which I want to iterate on. For each element of the array I want to execute a test with async/await functions, so I have this code:

const chai = require('chai');
const expect = chai.expect;

describe('Each film', async() => {

  await Promise.all([1, 2, 3].map(async(n) => {
    await new Promise(resolve => setTimeout(() => resolve(), 1000));
    console.log('N:', n);

    it('test', async() => {
      expect(true).to.be.true;
    });
  }));

});

执行此操作将产生以下输出:

Executing this results in the following output:

  0 passing (1ms)

N: 1
N: 2
N: 3

但是,如果我不使用异步/等待,它将按照我的期望执行,因此它将生成三个可以正确解决的测试.

However, if I don't use async/await it is executed as I would expect, so it generates three tests that are resolved correctly.

这里会发生什么?

更新

我终于发现 setTimeout 可用于异步加载数据,然后生成测试灵巧地.这是来自摩卡页面的解释:

I finally discovered that setTimeout can be used to load data asynchronously and then generate tests dinamically. This is the explanation from mocha page:

如果在运行任何套件之前需要执行异步操作,则可以延迟根套件.使用--delay标志运行摩卡咖啡.这会将特殊的回调函数run()附加到全局上下文:

If you need to perform asynchronous operations before any of your suites are run, you may delay the root suite. Run mocha with the --delay flag. This will attach a special callback function, run(), to the global context:

所以我最终以这种方式编写了代码:

So I finally wrote the code this way:

const chai = require('chai');
const expect = chai.expect;

setTimeout(async() => {
  await Promise.all([1, 2, 3].map(async(n) => {

    describe(`Element number ${n}`, () => {

      it('test', async() => {
        await new Promise(resolve => setTimeout(() => resolve(), 1000));
        expect(true).to.be.true;
      });

    });

  }));

  run();
}, 500);

它将生成以下输出:

➜ node_modules/.bin/mocha --delay test.js                                           


  Element number 1
    ✓ test (1005ms)

  Element number 2
    ✓ test (1001ms)

  Element number 3
    ✓ test (1002ms)


  3 passing (3s)

推荐答案

Mocha不支持异步describe函数.您可以动态生成测试,如此处所述,但是生成必须仍然是同步的.

Mocha does not support asynchronous describe functions. You can generate tests dynamically, as described here, but that generation must still be synchronous.

任何未同步创建的测试都不会被跑步者接受.因此,在输出顶部的0 passing行. Mocha决定在您的诺言兑现之前还没有任何测试.

Any tests that aren't created synchronously won't be picked up by the runner. Hence the 0 passing line at the top of your output. Mocha has decided there are no tests well before your promise resolves.

这并不是说不可能测试您的产品,只是您需要重新考虑如何使用Mocha对其进行测试.例如,以下内容类似于预先加载所有内容并在各种测试中对每个内容进行断言:

This isn't to say testing your stuff is impossible, just that you need to rethink how you're using Mocha to test it. The following, for example, would be similar to loading all of your things up front and making an assertion on each one in various tests:

const chai = require('chai');
const expect = chai.expect;

describe('Each item', () => {
    let items;

    before(async () => {
        items = [];
        await Promise.all([1, 2, 3].map(async(n) => {
            await new Promise(resolve => setTimeout(() => resolve(), 1000));
            items.push(n);
        }));
    })

    it('is a number', () => {
        for (item of items) {
            expect(item).to.be.a('number');
        }
    });

    it('is an integer', () => {
        for (item of items) {
            expect(item % 1).to.equal(0)
        }
    });

    it('is between 1 and 3', () => {
        for (item of items) {
            expect(item).to.be.within(1, 3)
        }
    });
});

不幸的是,您将无法在每个项目的输出中进行完全独立的测试显示.如果需要,您可以签出另一个测试运行程序.我真的没有与其他人的足够经验来说他们中的任何一个是否支持这一点.但是,如果他们这样做,我会感到惊讶,因为这很不寻常.

Unfortunately you won't be able to make a fully separate test displaying in your output for each item. If you want this, you may check out another test runner. I don't really have enough experience with others to say whether or not any of them support this. I'd be surprised if they do, though, since it's quite unusual.

这篇关于异步回调中的Mocha测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆