Jest结果嘲笑 - 如何

时间:2018-04-05 09:57:54

标签: unit-testing testing jestjs

我正在寻找有关如何在使用可以重复使用的Jest时模拟结果对象的最佳实践。

例如: 案例1 - 使用beforeEach的地方使用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);
        });
    });
});

案例2 - 将常量文件还原为执行删除的函数文件

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;
}

我更热衷于使用第一个选项,调用beforeEach并“深入克隆”对象,但同事坚持使用函数。

关于这个的想法?

注意为了便于阅读而修剪版本

0 个答案:

没有答案