2017-08-17 5 views
-1

Je suis en train d'ajouter des tests unitaires pour cette fonction:Comment ajouter des tests unitaires pour Javascript fonction hasOwnProperty()

var advance = function (des, source) { 
     for (var p in source) { 
      if (source.hasOwnProperty(p)) { 
       des[p] = source[p]; 
      } 
     } 
     return des; 
}; 

Comment vérifier la méthode hasOwnProperty() dans Jasmine?

Edit: Solution possible

var des; 
var source; 
beforeEach(function() { 
    des = {}; 
    source = { 
     p: 'value', 
     p1: 'value1' 
    }; 
}); 

beforeAll(function() { 
    advance(des, source); 
}); 

it('should has a property with the name of the argument', function() { 
    expect(source).toEqual(jasmine.objectContaining({ 
     p: 'value' 
    })); 
    expect(source).not.toEqual(jasmine.objectContaining({ 
     p2: 'value2' 
    })); 
}); 

Quelqu'un, s'il vous plaît suggérer une meilleure solution.

+0

Une meilleure solution à quoi? Quel est votre test unitaire actuel? –

+0

Et ne faites pas de marquage croisé. Java! = JavaScript! – GhostCat

+0

Quelle meilleure solution? Vous n'avez pas fourni votre propre tentative. –

Répondre

2

hasOwnProperty() renvoie la valeur true si le nom de propriété spécifié est seulement une partie de l'objet lui-même, et non sa chaîne prototype.

Ainsi, vous pouvez « simuler » un tel objet en créant une propriété sur le prototype comme celui-ci:

function Foo() { 
    // own properties of "src" 
    this.a = 1; 
    this.b = 2; 
} 
// not own property of "src" 
Foo.prototype.c = 1; 
src = new Foo(); 

test Vous pourrait ressembler à ceci:

describe("hasOwnProperty", function() { 
    var dest, src; 

    beforeEach(function() { 
     dest = { }; 

     function Foo() { 
      this.a = 1; 
      this.b = 2; 
     } 
     Foo.prototype.c = 3; 
     src = new Foo(); 

     advance(dest, src); 
    }); 

    it("should not pick non-own properties", function() { 
     expect(dest.c).not.toBeDefined(); 
    }); 

    it("should pick own property", function() { 
     expect(dest.a).toBe(1); 
     expect(dest.b).toBe(2); 
    }); 
}); 

Ceci échoue le test:

function Foo() { 
    this.a = 1; 
    this.b = 2; 
    // Own property - spec demands this to be undefined 
    this.c = 3; 
} 
// Defined (above) as own property instead 
// Foo.prototype.c = 3; 
src = new Foo(); 
+0

Merci pour la belle explication :) – supun94