2017-04-07 27 views
1

我是茉莉花 - 卡瑪。所以試圖找出如何執行下面的情況。篩選對象並返回茉莉花計數

這工作得很好

describe("jasmine.objectContaining", function() { 
    var foo; 

    beforeEach(function() { 
    foo = { 
     a: 1, 
     b: 2, 
     bar: "baz" 
    }; 
    }); 

    it("matches objects with the expect key/value pairs", function() { 
    expect(foo).toEqual(jasmine.objectContaining({ 
     bar: "baz" 
    })); 
    }); 
}); 

但現在如果我改變物體對象的數組這是行不通的。 那麼,如何從對象數組中過濾並返回計數。

例如。

describe("jasmine.objectContaining", function() { 
     var foo; 

     beforeEach(function() { 
     foo = [{ 
      a: 1, 
      b: 2, 
      bar: "baz" 
     }, 
     { 
      a: 1, 
      b: 2, 
      bar: "bdd" 
     } 

     ]; 
     }); 

     it("matches objects with the expect key/value pairs", function() { 
     expect(foo).//find object(s) containing bar:"baz" and it should return count=1 
     })); 
     }); 
}); 

回答

1

沒有jasmine.objectContaining它可以實現我們:

describe("array.filter returns entries", function() { 
 
    var foo; 
 

 
    beforeEach(function() { 
 
    foo = [{ 
 
     a: 1, 
 
     b: 2, 
 
     bar: "baz" 
 
     }, 
 
     { 
 
     a: 1, 
 
     b: 2, 
 
     bar: "bdd" 
 
     } 
 
    ]; 
 
    }); 
 

 
    it("matched by key/value", function() { 
 
    expect(foo.filter(function(element) { 
 
     return element.bar === 'baz' 
 
    }).length).toBe(1); 
 
    }); 
 
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" /> 
 
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>