JasmineJS - Matchers

Jasmine è un framework di test, quindi mira sempre a confrontare il risultato del file o della funzione JavaScript con il risultato atteso. Matcher funziona in modo simile nel framework Jasmine.

Matcherssono la funzione JavaScript che esegue un confronto booleano tra un output effettivo e un output previsto. Esistono due tipi di abbinamentiInbuilt matcher e Custom matchers.

Matcher integrato

Vengono chiamati i matcher incorporati nel framework Jasmine inbuilt matcher. L'utente può usarlo facilmenteimplicitly.

L'esempio seguente mostra come funziona Inbuilt Matcher nel framework Jasmine. Abbiamo già utilizzato alcuni matcher nel capitolo precedente.

describe("Adding single number ", function () {  

   //example of toEqual() matcher    
   it("should add numbers",function() { 
      expect(nested.add(5)).toEqual(5); 
      expect(nested.add(5)).toEqual(10); 
   });   
   
   it("should add numbers",function() { 
      expect(nested.addAny(1,2,3)).toEqual(6); 
   });
}

Nell'esempio toEqual () è il matcher integrato che confronterà il risultato di add() e addAny() metodi con gli argomenti passati a toEqual() fiammiferi.

Matcher personalizzati

I matcher che non sono presenti nella libreria di sistema integrata di Jasmine sono chiamati come custom matcher. È necessario definire il matcher personalizzatoexplicitly(). Nel seguente esempio, vedremo come funziona il matcher personalizzato.

describe('This custom matcher example', function() {
   
   beforeEach(function() { 
      // We should add custom matched in beforeEach() function. 
      jasmine.addMatchers ({ 
         validateAge: function() { 
            Return {    
               compare: function(actual,expected) {
                  var result = {}; 
                  result.pass = (actual > = 13 && actual < = 19);
                  result.message = 'sorry u are not a teen ';
                  return result; 
               }   
            };   
         }    
      });    
   }); 
    
   it('Lets see whether u are teen or not', function() { 
      var myAge = 14; 
      expect(myAge).validateAge();         
   });   
    
   it('Lets see whether u are teen or not ', function() { 
      var yourAge = 18;
      expect(yourAge).validateAge();  
   });
});

Nell'esempio sopra, validateAge()funziona come un matcher che in realtà convalida la tua età con un certo intervallo. In questo esempio, validateAge () funziona come un matcher personalizzato. Aggiungi questo file JS inSpecRunner.htmle corri lo stesso. Genererà il seguente output.