it 语句在每个 expect 语句的循环迭代中,mocha

it statement inside loop iteration for each expect statement, mocha

我有这个对象数组。

let links = [
  { 
   url: 'some url 1',
   status: 200 
  },
  {
   url: 'some url 2',
   status: 200 
  }
] 

这是在before内部异步调用LinkFunction的结果:

  before(async () => {
    try {
      links = await LinkFunction();
    } catch (err) {
      assert.fail(err);
    }
  });

我想检查 urlstatus 属性是否存在,以及它们的类型是否相应地为字符串和数字。
注意:指定的对象只是大响应的一个示例。所以无论如何迭代都需要循环。

我已经完成了这个迭代:

  it('Array to contain some props', () => {
    links.map(property => {
      expect(property).to.have.property('url').to.be.a('string');
      expect(property).to.have.property('status').to.be.a('number');
    });
  });

但我想要这样的东西:

it('Array to contain some props', () => {//or describe would be better here
  links.map(property => {
    it('link array to contain url string', () => {
      expect(property).to.have.property('url').to.be.a('string');
    });
    it('link array to contain status number', () => {
      expect(property).to.have.property('status').to.be.a('number');
    });
  });
});

不幸的是 it 语句在地图中被忽略。也许是因为有几个嵌套的 it 语句。那么我该如何实现类似的逻辑呢?

更新:

My full code:

您可能想使用 forEach 而不是 map

此外,"Passing arrow functions (aka "lambdas") to Mocha is discouraged" 因此您可能希望将它们更改为正常功能。

话虽如此,如果 links 被定义为 mocha 最初运行测试文件并收集个人 it 测试,它工作正常:

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

describe('links', function() {
  let links = [
    { 
     url: 'some url 1',
     status: 200 
    },
    {
     url: 'some url 2',
     status: 200 
    }
  ]

  links.forEach(function(property) {
    it('link array to contain url string', function() {
      expect(property).to.have.property('url').to.be.a('string');
    });
    it('link array to contain status number', function() {
      expect(property).to.have.property('status').to.be.a('number');
    });
  });
});

..结果为:

> mocha



  links
    √ link array to contain url string
    √ link array to contain status number
    √ link array to contain url string
    √ link array to contain status number


  4 passing (14ms)

更新

如您所见,it 仅适用于顶层或 describe:

before(function() {
  it('will NOT work here', function() { });
});

it('will work here', function() {
  it('will NOT work here', function() { });      
});

此外,links 必须可用,而测试是第一个 运行 并且 it 测试由 mocha 收集,因此这也不起作用:

describe('links', function() {

  let links = [];

  before(function() {
    links = [
      { 
       url: 'some url 1',
       status: 200 
      },
      {
       url: 'some url 2',
       status: 200 
      }
    ];
  });

  // This won't work...
  links.forEach(function(property) {
    // .. since links is still an empty array when this runs
    it('should...', function() { /* ... */ });
  });

});

从您的问题更新来看,您的代码似乎从 before 中的 async 函数调用中检索 links。因此,无法在测试首次 运行 和收集 it 测试时填充 links

因此看起来您将无法映射 links 中的项目来创建您的 it 测试,而是需要采用您描述的映射方法单次测试中 links 项。