Home > database >  Use constants or no for expectations in tests?
Use constants or no for expectations in tests?

Time:07-24

For example, we have some big page that we testing, and for test we have big mock. And one of our expectations - check value of product price. It can be done like:

expect(price).toBe(20);

Or, we can use value directly from mock:

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

Or define additional variable like:

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

Which way will be preferrable?

CodePudding user response:

I believe both ways are ok in your scenario, however I would declare const mostly when I have multiple attributes, in order to avoid repeat orderMock.data.user.order too many.

Sometimes you can use object destructuring as well, when you have more attributes:

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

Just keep in mind if you do something similar with methods you may lose your bind.

CodePudding user response:

I appreciate second way a lot more, cause its re-useable and it's says about it self - variable names are like descriptions

PS: In my opinion you should use var instead of const cause many older browsers dont fully support const https://caniuse.com/?search=const If im right const is full supported since ECMA 6

  • Related