简体   繁体   中英

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.

If the result is complicated data structure, calculate manually is not a good idea. I could make a mistake about the result .

So, what's the "correct" way to simulate the expect result?

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. To test the SUT you must know before hand what the final outcome should be . This is why it advisable to test the SUT result with a simple stubbed expected value, something that you are confident is correct . 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. Hope this answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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