使用Chai / Mocha检查JSON数组中的值

时间:2018-04-26 16:22:57

标签: mocha chai

我有一个函数是返回JSON数组的js

[
    {
        "coordinates": {
            "lat": 1,
            "lng": 2
        },
        "name": "33301 - Fort Lauderdale, Florida"
    },
    {
        "coordinates": {
            "lat": 3,
            "lng": 4
        },
        "name": "33301 - Atlanta, Georgia"
    }
]

如何编写Chai expect语句来检查名称值...

基本上,我想查看结果名称参数是否包含“33301 - Atlanta,Georgia”

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您可以过滤出数据并进行验证:

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d = {k: oldk for oldk, oldv in labels_dict.items() for k in oldv}
df['labels'] = df['criterion'].map(d)
print(df)
   year  criterion   labels
0  2014          1  label_1
1  2014          2  label_1
2  2015          3      NaN
3  2015          4  label_2
4  2016          5      NaN
5  2016          6  label_2

答案 1 :(得分:0)

查看有关断言的官方文档:

// Target object deeply (but not strictly) includes `x: {a: 1}`
expect({x: {a: 1}}).to.deep.include({x: {a: 1}});
expect({x: {a: 1}}).to.not.include({x: {a: 1}});


// Target object deeply (but not strictly) has property `x: {a: 1}`
expect({x: {a: 1}}).to.have.deep.property('x', {a: 1});
expect({x: {a: 1}}).to.not.have.property('x', {a: 1});


// Target array deeply (but not strictly) has member `{a: 1}`
expect([{a: 1}]).to.have.deep.members([{a: 1}]);
expect([{a: 1}]).to.not.have.members([{a: 1}]);

http://www.chaijs.com/api/bdd/

还有用于测试json文件的chai-json插件,如下所示:

expect(testFile).to.be.a.jsonFile().and.contain.jsonWithProps({ repoName: 'giper' });

详细了解如何制作断言:http://www.chaijs.com/plugins/chai-json/