在测试中使用常数还是不使用期望值



例如,我们有一些大页面要测试,而对于测试,我们有大mock。我们的期望之一——检查产品价格的价值。可以这样做:

expect(price).toBe(20);

或者,我们可以直接使用mock:中的值

expect(price).toBe(orderMock.data.user.order.price);

或者定义其他变量,如:

const expectedPrice = orderMock.data.user.order.price;
expect(price).toBe(expectedPrice);

哪种方式更可取?

我相信在您的场景中,这两种方法都可以,但当我有多个属性时,我会声明const,以避免重复orderMock.data.user.order过多。

当你有更多的属性时,有时你也可以使用对象析构函数:

const { price:expectedPrice, otherAttribute } = orderMock.data.user.order;
expect(price).toBe(expectedPrice);
expect(otherValue).toBe(otherAttribute);

请记住,如果你用类似的方法做一些事情,你可能会失去束缚

我更欣赏第二种方式,因为它是可重复使用的,而且据说自变量名称就像描述一样

PS:在我看来,你应该使用var而不是const,因为许多旧的浏览器并不完全支持consthttps://caniuse.com/?search=const如果自ECMA 6 以来完全支持im right const

最新更新