Sun Apr 30 2023

How to increase the resilience of test expectations by tapping into the test data

A quick way to increase the resilience of test expectations when the test data keeps changing

I won't go into a long-winded speel about why testing is important because there’s plenty of material written on it. 

As important as tests are, we sometimes spend way too much time maintaining them. I found myself in the same situation recently and wanted to find a quick way to reduce the need to update unit tests the moment that the test data changed. 

Here’s a simple example of such a test. All that we are testing here is the proper functioning of generateBetterCustomerData().

1const customerData = {
2 name: "James",
3 familyName: "Gulliver",
4 age: 29,
5 occupation: "engineer",
6 favouriteBook: "witcher",
7};
8const generateBetterCustomerData = ({
9 name,
10 familyName,
11 age,
12 occupation,
13 favouriteBook,
14}: typeof customerData) => {
15 return {
16 fullName: `${name} ${familyName}`,
17 age,
18 occupation,
19 favouriteBook,
20 };
21};
22describe("testing", () => {
23 it("tests generateBetterCustomerData()", () => {
24 expect(generateBetterCustomerData(customerData)).toEqual({
25 age: 29,
26 favouriteBook: "witcher",
27 fullName: "James Gulliver",
28 occupation: "engineer",
29 });
30 });
31});
32

Notice that anytime I changed a property in this customerData object for use in another test, this test would start failing as the hardcoded expectation is not met.

We can avoid this had the assertion value had been using the data from the customerData object itself. See below 

1describe("testing", () => {
2 it("tests generateBetterCustomerData()", () => {
3 expect(generateBetterCustomerData(customerData)).toEqual({
4 fullName: `${customerData.name} ${customerData.familyName}`,
5 age: customerData.age,
6 occupation: customerData.occupation,
7 favouriteBook: customerData.favouriteBook,
8 });
9 });
10});

Now, our test still does what we want it to do and is now resilient to any changes in the test data that is being passed into it 

Did you find this topic useful and/or have something else you'd like me to write about? Let me know in the comments below!

Comments