摩卡,如何处理测试用例重复代码?

时间:2017-01-22 03:25:15

标签: javascript unit-testing mocha

如您所见,我的测试用例有重复部分。

我该如何处理?只写一个常用的函数来重用?

mocha处理此问题的方法吗?

 it('test case 1', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        c: 1
    };
    expect(deepMerge(target, source)).to.deep.equal({a: 1, b: 1, c: 1});

    //dulplicate
    expect(target).to.eql(target);
    expect(source).to.eql(source);
});

it('test case 2', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        a: 2,
        c: 1
    };

    expect(deepMerge(target, source)).to.deep.equal({a: 2, b: 1, c: 1});
    //dulplicate
    expect(target).to.eql(target);
    expect(source).to.eql(source);
});
//more test cases also have the duplicate part.

1 个答案:

答案 0 :(得分:0)

您可以将所有重复的期望案例放在某个函数中,并在每个it块中调用该函数;

function duplicateTests(target, source) {
    expect(target).to.eql(target);
    expect(source).to.eql(source);
}; 

it('test case 1', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        c: 1
    };
    expect(deepMerge(target, source)).to.deep.equal({a: 1, b: 1, c: 1});

  duplicateTests(target, source);
});

it('test case 2', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        a: 2,
        c: 1
    };

    expect(deepMerge(target, source)).to.deep.equal({a: 2, b: 1, c: 1});
    duplicateTests(target, source);
});
//more test cases also have the duplicate part.