Node.js中的JSON过滤器和断言功能

时间:2018-11-14 13:23:30

标签: node.js api testing mocha

我从api收到以下响应:

{
    "fieldErrors": [
        {
            "field": "firstName",
            "code": "Pattern",
            "message": "Invalid characters"
        },
        {
            "field": "repeatPassword",
            "code": "Size",
            "message": "Size must be between 6 and 64 characters"
        },
        {
            "field": "password",
            "code": "Size",
            "message": "Size must be between 6 and 64 characters"
        },
        {
            "field": "firstName",
            "code": "Size",
            "message": "Size must be between 3 and 32 characters"
        },
        {
            "field": "lastName",
            "code": "Pattern",
            "message": "Invalid characters"
        },
        {
            "field": "email",
            "code": "Size",
            "message": "Size must be between 3 and 256 characters"
        },
        {
            "field": "password",
            "code": "AmRestUser.PasswordTooWeak",
            "message": "Password is to weak (must consist of upper and lower case, digits, and can't contain first name)."
        },
        {
            "field": "phoneNo",
            "code": "order.summary.invalidPhone",
            "message": "Invalid Phone"
        }
    ],
    "isSuccess": false
}

我使用Mocha编写api测试,我想检查所有现有错误的字段

我编写以下测试:

      var selected = res.body.fieldErrors.filter(function(item){
        return (item["field"]=="firstName" && item["code"] == "Pattern"  && item["message"]=="Invalid characters"); 
      });
      assert.equal(selected.length,1);

      selected = res.body.fieldErrors.filter(function(item){
        return (item["field"]=="repeatPassword" && item["code"] == "Size"  && item["message"]=="Size must be between 6 and 64 characters"); 
      });
      assert.equal(selected.length,1);

测试对我有用,但是有很多冗余代码,在这种情况下,我应该写相同的代码八次,很难维护

现在我想编写一个函数,在参数中我可以传递json以及代码,消息和字段的名称。函数应该返回出现的次数,我该怎么办?

1 个答案:

答案 0 :(得分:0)

您没有告诉我们使用哪个断言库,但这是执行此操作的最简单方法(无需任何其他功能或映射):

有关蔡的断言,请参见:https://developer.android.com/topic/libraries/architecture/workmanager/ 例如:assert.deepEqual(res.body, expected)

有关node.js的断言,请参见:deepEqual 例如:assert.deepStrictEqual(res.body, expected)

expected与您在第一个代码段中粘贴的对象保持一致。或者当然可以将其更改为fieldErrors数组。由您决定。

使用此方法,您仅需要维护一些错误列表即可。