mardi 29 août 2017

How to test existence of parent object before testing value or child

What would be the best way to test for the existence of a deeply nested property using Jest. Trying to target the particular object I want will get me an undefined error because its parent object doesn't exist:

test('returns data from `server/index.js`', () => {
  const data = axios.get(httpObj)
     .then(data, => {
        expect(data.els[4]).not.toBeNull() 
        // ^ TypeError: Cannot read property '4' of undefined
  })
})

Should I chain these in some way so I can first test for the existence of the object, then test for the existence of the inner object? The equivalent of doing something like this in an if-statement

if (obj && obj[4] && obj[4].hasOwnProperty('myProp')) {
  // pass
}

Or when doing multiple tests on one element like this, should there be separate tests?

test('returns data from `server/index.js`', () => {
  const data = axios.get(httpObj)
     .then(data, => {
        expect(data).not.toBeNull() 
  })
})

test('data returned from `server/index.js` api contains my property', () => {
  const data = axios.get(httpObj)
     .then(data, => {
        expect(data.els[4]).not.toBeNull() 
  })
})

I have also tried:

const expected = {/* very large object */}
test('returns data from `server/index.js` and it contains an array containing the `expected` object', () => {
  expect(data.els[4]).toEqual(
    expect.objectContaining(expected)
  )
})

This works a bit? better, but requires me to have this very large object declared within the test file. This very deep comparison combined with just a static blob of data in my test file feels brittle to me. Is there a more canonical way than what I've tried

Aucun commentaire:

Enregistrer un commentaire