简体   繁体   English

摩卡咖啡和柴,我怎么能嘲笑预期的结果?

[英]mocha & chai, how can I mock expect result?

My source code: 我的源代码:

function getElementCountOfArray(arr) {
    var countObj = {};
    arr.forEach((element) => {
        if(countObj[element]) {
            countObj[element] ++;
        } else {
            countObj[element] = 1;
        }
    });

    return countObj;
}

module.exports = getElementCountOfArray;

my test code: 我的测试代码:

describe('getElementCountOfArray', function() {

    it('test case 1', function() {
        var numArray = [2, 2, 3, 6, 7, 7, 7, 7, 8, 9];

        var result = {
            2: 2,
            3: 1,
            6: 1,
            7: 4,
            8: 1,
            9: 1
        };

        expect(getElementCountOfArray(numArray)).to.eql(result);
    });
});

the result is calculate by myself, I really think is not correct. result是我自己计算的,我真的认为是不正确的。

If the result is complicated data structure, calculate manually is not a good idea. 如果result是复杂的数据结构,则手动计算不是一个好主意。 I could make a mistake about the result . 我可能对result有误。

So, what's the "correct" way to simulate the expect result? 那么,模拟expect结果的“正确”方法是什么?

I would say this how the unit tests are supposed to work. 我要说的是单元测试应该如何工作。 The result that is returned by your SUT(System Under Test) ie the method you are testing, is a product of the processing done in the SUT. SUT(被测系统)返回的结果(即您正在测试的方法)是在SUT中完成处理的结果。 To test the SUT you must know before hand what the final outcome should be . 要测试SUT, 您必须事先知道最终结果是什么 This is why it advisable to test the SUT result with a simple stubbed expected value, something that you are confident is correct . 这就是为什么建议使用简单的预期残值来测试SUT结果的原因,您确信这是正确的 Of course, some results can be complicated data structures, but you can choose to stub the expected structure using just one or two elements. 当然,某些结果可能是复杂的数据结构,但是您可以选择仅使用一个或两个元素对期望的结构进行存根。

Again, the expected value, no matter how complex, must be easily verifiable and simple enough to be able for someone to arrive at using a dry run of the SUT. 再次,期望值,无论多么复杂,都必须易于验证和简单到足以使某人能够使用空运行的SUT到达。 Hope this answers your question. 希望这能回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM