5

I don't know if this has a sort review process, but here goes (direct me elsewhere if appropriate)

I have written these tests, and wondered if my use of Given, When and Then was correct.

I ask because it just seems I get one when per expectation - does everyone else find this - or do I just have an overly simplified example.

describe('Feature: Array Comparer', () => {
    const Subject = (arr1, arr2) => {
        return compare(arr1, arr2);
    };

    describe('Given two identical arrays', () => {
        const arrayOne = [{
            value: 2
        }, {
            value: 1
        }];

        const arrayTwo = [{
            value: 1
        }, {
            value: 2
        }];

        describe('When comparing them', () => {
            const result = Subject(arrayOne, arrayTwo);

            it('should return true', () => {
                expect(result).toBe(true);
            });

        });

    });

    describe('Given two different arrays', () => {
        const arrayOne =[{
            value: 3
        }, {
            value: 1
        }];

        const arrayTwo = [{
            value: 3
        }, {
            value: 5
        }];

        describe('When comparing them', () => {
            const result = Subject(arrayOne, arrayTwo);

            it('should return false', () => {
                expect(result).toBe(false);
            });
        });
    });

    describe('Given one empty array', () => {
        const arrayOne = [{
            value: 1
        }, {
            value: 3
        }];

        const arrayTwo = [];

        describe('When comparing them', () => {
            const result = Subject(arrayOne, arrayTwo);

            it('should return false', () => {
                expect(result).toBe(false);    
            });
        });
    });

});

The output being:

test output

2

One assertation ('then') per test is a good thing and generally considered a best practice.

It may seem a bit wordy and long but the idea is that when it fails you know exactly and specifically what the issue is.

The frequent exception to this is UI tests which use multiple assertions per test, mostly in the interest of time as they run slowly due to bringing up an actual browser.

Techniques you can use include nesting describes (as you have done) and using before :each for setup to be repeated for the containing tests.

  • So what I'm doing is pretty common then. Do you think i'm using them in the correct way – Callum Linington Jul 17 '17 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.