首页 > 解决方案 > 使用等待时跳过“描述”

问题描述

第二级描述在关于在其中使用 await 的报告中被跳过。

我有一个测试结构,我在测试中以多个级别异步读取文件并使用数据进行验证。

这是我的代码的过度简化版本,请原谅。这个想法是在测试中进行多个异步调用以读取多个级别的文件。


const { expect } = require('chai');

const subList1 = [
  { title: 'subList1_title1', value: '1' },
  { title: 'subList1_title2', value: '2' },
  { title: 'subList1_title3', value: '3' },
];
const subList2 = [
  { title: 'subList2_title1', value: '1' },
  { title: 'subList2_title2', value: '2' },
  { title: 'subList2_title3', value: '3' },
];

const masterList = [
  {
    title: 'subList1',
    value() {
      return subList1;
    },
  },
  {
    title: 'subList2',
    value() {
      return subList2;
    },
  },
];

function getMasterList() {
  return masterList;
}

describe('All Tests', async function () {
  let testMasterList = [];
  testMasterList = await getMasterList();
  testMasterList.forEach(function (item) {
    describe(item.title, async function () {
      const list = await item.value();
      list.forEach(function (element) {
        describe(element.title, function () {
          it('Value should be a string', function () {
            expect(element.value).to.be.a('string');
          });
        });
      });
    });
  });
});
setTimeout(function () {
  run();
}, 1000);

我使用带有 mocha 的 --delay 标志来运行测试。

如果我删除第二个await,那么所有描述都会打印在控制台中。

预期的:

  subList1
    subList1_title1
      ✓ Value should be a string
    subList1_title2
      ✓ Value should be a string
    subList1_title3
      ✓ Value should be a string

  subList2
    subList2_title1
      ✓ Value should be a string
    subList2_title2
      ✓ Value should be a string
    subList2_title3
      ✓ Value should be a string

实际的:

subList1_title1
    ✓ Value should be a string

  subList1_title2
    ✓ Value should be a string

  subList1_title3
    ✓ Value should be a string

  subList2_title1
    ✓ Value should be a string

  subList2_title2
    ✓ Value should be a string

  subList2_title3
    ✓ Value should be a string

标签: loopsasynchronousasync-awaitmocha.js

解决方案


再看看mocha gitter,我试图在那里回答你的问题。问题在于动态套件/测试生成:您需要首先检索生成测试所需的所有数据,因此如果测试或套件名称中有变量,则需要预先加载。或者,如果您静态定义测试,那么您可以在挂钩中或在测试本身中加载异步数据。这是给你的

// Load all data required for suite/test generation first
getMasterList()
  .then(function(testMasterList) {
    testMasterList.forEach(async function(item) {
      item.loaded = await item.value();
    })
    return testMasterList;
  })
  .then(function(testMasterList) {

    describe('All Tests', function () { // Describe is not async, ever...

      testMasterList.forEach(function(item) {
        describe(item.title, function() {
          const list = item.loaded; // Loaded previously in promise form
          list.forEach(function(element) {
            describe(element.title, function() {
              it('Value should be a string', function() {
                chai.expect(element.value).to.be.a('string');
              });
            });
          });
        });
      });
    });
  });

推荐阅读