Javascript 每个expect语句的循环迭代中的it语句,mocha
我有这个对象数组Javascript 每个expect语句的循环迭代中的it语句,mocha,javascript,mocha.js,Javascript,Mocha.js,我有这个对象数组 let links = [ { url: 'some url 1', status: 200 }, { url: 'some url 2', status: 200 } ] 这是在之前的中异步调用LinkFunction的结果: before(async () => { try { links = await LinkFunction(); } catch (err) { ass
let links = [
{
url: 'some url 1',
status: 200
},
{
url: 'some url 2',
status: 200
}
]
这是在之前的中异步调用LinkFunction的结果:
before(async () => {
try {
links = await LinkFunction();
} catch (err) {
assert.fail(err);
}
});
我想检查url
和status
属性是否存在,以及它们的类型是否为相应的字符串和数字。
注意:指定的对象只是一个大响应的示例。因此,在任何情况下,迭代都需要循环
我已经完成了这个迭代:
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
语句在map中被忽略。可能是因为几个嵌套的it语句。那么,我如何实现类似的逻辑呢
更新:
您可能希望使用forEach
而不是map
此外,您可能希望将这些函数更改为正常函数
话虽如此,如果links
定义为mocha
则可以正常工作,首先运行测试文件并收集单个it
测试:
const expect=require('chai')。expect;
描述('links',function()){
让链接=[
{
url:“某些url 1”,
现状:200
},
{
url:'一些url 2',
现状:200
}
]
links.forEach(函数(属性){
它('链接数组以包含url字符串',函数(){
expect(property).to.have.property('url').to.be.a('string');
});
它('链接数组以包含状态号',函数(){
expect(property).to.have.property('status').to.be.a('number');
});
});
});
…结果:
摩卡咖啡
链接
√ 链接数组以包含url字符串
√ 链接数组以包含状态号
√ 链接数组以包含url字符串
√ 链接数组以包含状态号
4次通过(14毫秒)
更新
正如您所发现的,它只在顶层工作,或者使用描述:
before(函数(){
它('will NOT work here',function(){});
});
它('will work here',function(){
它('will NOT work here',function(){});
});
此外,链接
必须在测试首次运行时可用,并且it
测试由mocha
收集,因此这也不起作用:
description('links',function()){
让链接=[];
在(函数()之前){
链接=[
{
url:“某些url 1”,
现状:200
},
{
url:'一些url 2',
现状:200
}
];
});
//这行不通。。。
links.forEach(函数(属性){
//…因为运行此操作时链接仍然是空数组
它('should…',function(){/*…*/});
});
});
从您的问题更新中,您的代码似乎从之前的异步函数调用中检索链接。因此,无法在测试首次运行时填充链接
,也无法收集it
测试
因此,您似乎无法通过映射链接中的项目来创建it
测试,而是需要采用您描述的方法,在单个测试中映射链接中的项目。映射中的项目似乎工作正常(至少在我在线找到的这个游乐场上)-你能解释一下“忽略”是什么意思吗?可能是因为我的代码中有描述。我会更新代码请查看更新的问题。这是因为嵌套的It
statements@undefinedUser我根据您更新的问题更新了下面的答案