jeudi 5 avril 2018

Jest Result mocking - how to's

I'm looking for best practice on how to mock result objects when using Jest that can be reused.

for example: CASE 1 - Where I use beforeEach as populate the objects using deepclone

describe('When requesting the exterior details', () => {
    let car;
    beforeEach(() => {
        car = testHelper.deepClone(mocks.car);
        exteriorMock = testHelper.deepClone(mocks.exterior);
    })

     describe('and we have a price for the exterior colour', () => {
        test('Then all values are filled in properly from the configuration', () => {
            const result = helper.getExteriorColour(car);
            expect(result).toEqual(exteriorMock);
        });
    });

    describe('and the price object is missing', () => {
        test('then the price is ignored', () => {
            delete car.exterior.price;
            delete exteriorMock.price;

            const result = helper.getExteriorColour(car)
            expect(result).toEqual(exteriorMock);
        });
    });
});

CASE 2 - Where the constants file is reverted to a functions file that does the delete

describe('When requesting the exterior details', () => {
     describe('and we have a price for the exterior colour', () => {
        const car = mocks.getCar();
        const exteriorMock = mocks.getExteriorMock();
        test('Then all values are filled in properly from the configuration', () => {
            const result = helper.getExteriorColour(car);
            expect(result).toEqual(exteriorMock);
        });
    });

    describe('and the price object is missing', () => {
        const car = mocks.getCarNoPrice();
        const exteriorMock = mocks.getExteriorMockNoPrice();
        test('then the price is ignored', () => { 
            const result = helper.getExteriorColour(car)
            expect(result).toEqual(exteriorMock);
        });
    });
});

//In the mock file then
export function getCar() {
    return {
        name: "mycar" ,
        price: {
            value: 9000
        }
    }
}

export function getCarNoPrice() {
    const car = getCar();
    delete car.price;
    return car;
}

I'm more keen to use the first option in this, calling the beforeEach and "deep cloning" the objects that way, but a colleague insists on using functions for it.

Thoughts about this?

note trimmed down version for readability

Aucun commentaire:

Enregistrer un commentaire