Frisby.js testing with optional array of objects

1.1k views Asked by At

How can you use Frisby.js to test an optional array that contains objects? For example, say we have an API call that returns something like this:

{
  "id": "123",
  "type": "A",
  "list": [
      {
         "id": "111",
         "size": 1
      }, 
      {
         "id": "222",
         "size": 2
      }
  ]
}

However, it may also return something like this:

{
  "id": "456",
  "type": "B"
}

Currently, I'm trying:

const frisby = require('frisby');
const Joi = frisby.Joi;

test('myTest', () => {
    return frisby
        .get(myUrl)
        .expect('status', 200)
        .expect('jsonTypes', {
            id: Joi.string().required(),
            type: Joi.string().required().
            list: Joi.array().optional()
        })
        .expect('jsonTypes', 'list.*', {
            id: Joi.string().required(),
            size: Joi.number().required()
        });
});

This won't work, however, since the path (list.*) won't be defined if the list attribute doesn't exist. Any ideas?

2

There are 2 answers

0
Connor On

I have a work around until someone figures out a more efficient method. This method just seems inefficient because it requires multiple API calls. The gist is to first check if the optional array exists. If so, you can use another API call and use the path to make the appropriate checks.

const frisby = require('frisby');
const Joi = frisby.Joi;

test('myTest', () => {
    return frisby
    .get(myUrl)
    .expect('status', 200)
    .expect('jsonTypes', {
        id: Joi.string().required(),
        type: Joi.string().required().
        list: Joi.array().optional()
    })
    .then(function (response) {
        if(response._json.list) {
            return frisby
                .get(myUrl)
                .expect('jsonTypes', 'list.*', {
                    id: Joi.string().required(),
                    size: Joi.number().required()
                });
        }
    });
});
0
DevArti On

By this way you can do that :

     .expect('jsonTypes',"data", {
        id: Joi.number(),
        type: Joi.string()
     })
    .expect('jsonTypes', "data.list",Joi.array().items({
        "id": Joi.number(),
        "size": Joi.number()    
    }))
    .then(function(res) {
        var body = res.body;
        body = JSON.parse(body);

    expect(body.data.id).toBeDefined();
    expect(body.data.type).toBeDefined();
    if(body.data.list)  {   
    for(var i = 0; i < body.data.list.length; i++){
    expect(body.data.list[i].id).toBeDefined();
    expect(body.data.list[i].type).toBeDefined();
    }
}