2015-12-21 11 views
7

Sto cercando di convalidare che un array di oggetti come questo:Chai si aspettano: una matrice per contenere un oggetto con almeno queste proprietà e valori

[ 
    { 
     a: 1, 
     b: 2, 
     c: 3 
    }, 
    { 
     a: 4, 
     b: 5, 
     c: 6 
    }, 
    ... 
] 

contiene almeno un oggetto con entrambi { a: 1 } e { c: 3 } :

ho pensato che avrei potuto fare questo con chai-things, ma non so tutte le proprietà dell'oggetto per essere in grado di utilizzare

expect(array).to.include.something.that.deep.equals({ ??, a: 1, c: 3}); 

e contain.a.thing.with.property non funzionano con più proprietà:/

Qual è il modo migliore per testare qualcosa del genere?

risposta

4

soluzione più elegante ho potuto venire con (con l'aiuto di lodash):

aspettano (_ qualche (array, { 'a': 1, 'c': 3}.)). to.be.true;

0

È possibile scrivere la propria funzione per testare la matrice. In questo esempio, si passa nella matrice e l'oggetto che contiene le relative coppie chiave/valore:

function deepContains(arr, search) { 

    // first grab the keys from the search object 
    // we'll use the length later to check to see if we can 
    // break out of the loop 
    var searchKeys = Object.keys(search); 

    // loop over the array, setting our check variable to 0 
    for (var check = 0, i = 0; i < arr.length; i++) { 
    var el = arr[i], keys = Object.keys(el); 

    // loop over each array object's keys 
    for (var ii = 0; ii < keys.length; ii++) { 
     var key = keys[ii]; 

     // if there is a corresponding key/value pair in the 
     // search object increment the check variable 
     if (search[key] && search[key] === el[key]) check++; 
    } 

    // if we have found an object that contains a match 
    // for the search object return from the function, otherwise 
    // iterate again 
    if (check === searchKeys.length) return true; 
    } 
    return false; 
} 

deepContains(data, { a: 4, c: 6 }); // true 
deepContains(data, { a: 1, c: 6 }); // false 

DEMO

0

La soluzione desiderata sembra essere qualcosa di simile:

expect(array).to.include.something.that.includes({a: 1, c: 3}); 

Vale a dire array contiene un elemento che include tali proprietà. Sfortunatamente, al momento sembra not be supported by chai-things. Per il prossimo futuro.

Dopo numerosi tentativi, ho scoperto che la conversione dell'array originale semplifica l'attività. Questo dovrebbe funzionare senza librerie aggiuntive:

// Get items that interest us/remove items that don't. 
const simplifiedArray = array.map(x => ({a: x.a, c: x.c})); 
// Now we can do a simple comparison. 
expect(simplifiedArray).to.deep.include({a: 1, c: 3}); 

Questo permette anche di verificare la presenza di più oggetti allo stesso tempo (il mio caso d'uso).

expect(simplifiedArray).to.include.deep.members([{ 
    a: 1, 
    c: 3 
}, { 
    a: 3, 
    c: 5 
}]); 
Problemi correlati