mercredi 14 novembre 2018

JSON filter&assert function in Node.js

i receive following response from 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
}

I writing api tests in using Mocha and i want to check fields of all existing errors

I write following tests:

      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);

Tests works for me, but there is lot of a redundant code, in this case i should write same code eight times, it is difficult to maintain

Now i want to write one function, in parameters I could pass json, and names of code, message and field. Function should return the number of occurrences, how can i do it?

Aucun commentaire:

Enregistrer un commentaire