gpbaculio
gpbaculio

Reputation: 5968

how to make sure all items in an array of objects has all required keys in mocha?

i'm new in testing and i have a result of array of objects and i want to make sure each item in an array has required properties, the result is like this:

// result_threads = [{a:1,b:2},{a:3,b:4}]

and i want to make a test like this:

chai_module
      .request(server)
      .get(`/api/threads/${test_board_id}`)
      .end((get_threads_error, response) => {
        const { status: actual_status } = response;
        const { threads: result_threads } = response.body
        // THE TEST I WANT TO MAKE
        assert.isArray(result_threads).to.contain.an.item.hasAllKeys(['a','b']);


        done();
      });

how do i make sure that an item in an array has all keys required?

Upvotes: 0

Views: 218

Answers (1)

Murat
Murat

Reputation: 1205

One way to do it can be to verify the assertions in two steps. You first verify that you have an array, and then you iterate through the array and verify that each item has the keys you are expecting :

chai_module
  .request(server)
  .get(`/api/threads/${test_board_id}`)
  .end((get_threads_error, response) => {
    const { status: actual_status } = response;
    const { threads: result_threads } = response.body

    assert.isArray(result_threads);
    result_threads.forEach((item) => {
       assert.hasAllKeys(item, ['a', 'b']);
    });

    done();
  });

Upvotes: 1

Related Questions