我们如何添加Java单元测试hasOwnProperty()函数

sup*_*n94 0 javascript unit-testing jasmine karma-jasmine

我正在尝试为此功能添加单元测试:

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

我们如何检查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'
    }));
});
Run Code Online (Sandbox Code Playgroud)

有人,请提出任何更好的解决方案。

try*_*lly 5

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();
Run Code Online (Sandbox Code Playgroud)

您进行的测试可能如下所示:

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);
    });
});
Run Code Online (Sandbox Code Playgroud)

这将使测试失败:

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();
Run Code Online (Sandbox Code Playgroud)