我试图为此功能添加单元测试:
var advance = function (des, source) {
for (var p in source) {
if (source.hasOwnProperty(p)) {
des[p] = source[p];
}
}
return des;
};
我们如何检查Jasmine中的hasOwnProperty()
方法?
编辑: 可能的解决方案
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'
}));
});
有人,请建议任何更好的解决方案。
答案 0 :(得分:4)
hasOwnProperty()
返回true。
因此你可以"模拟"这样的对象是通过在原型上创建一个属性,如下所示:
function Foo() {
// own properties of "src"
this.a = 1;
this.b = 2;
}
// not own property of "src"
Foo.prototype.c = 1;
src = new Foo();
您的测试可能如下所示:
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);
});
});
这将无法通过测试:
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();