dimanche 5 juillet 2020

Advice needed: Writing JavaScript unit test suite descriptions [closed]

I’m in between minds when writing my descriptions for my JavaScript unit test suites. I’d welcome some advice / opinions on the best route (if there is one).

For clarity let’s use a simple add() function as an example.

function add(x, y) {
  return x + y;
}

I have two proposed options for writing my tests:

Describe the expected behaviour of add()
We can write a short description on what we expect from our add() function.

Let’s write an example:

describe(“add() - when passing valid values of type ‘number’ to parameters ‘x’ and ‘y’”, () => {
  it(“should return the sum of parameters ‘x’ and ‘y’”, () => {
   expect( add(1, 2) ).toBe(3); // Pass
  });
});

Here we can see we’re describing the expected behaviour of add(), i.e it should return the sum of the parameters. However, this can lead to false positives, for example if someone was to hard code add() to return 3.

This leads us onto option two...

Describe the expected result of add()
To mitigate any false positives we could run multiple suites to test add(), however we can’t just replicate the description of the suite in the example above. Instead we need to describe the expected result.

Let’s write another example:

describe(“add() - when passing valid values of type ‘number’ to parameters ‘x’ and ‘y’”, () => {
  it(“should return `3` when passed a value of ‘1’ to parameter ‘x’ and a value of ‘2’ to parameter ‘y’”, () => {
   expect( add(1, 2) ).toBe(3); // Pass
  });

  it(“should return `5` when passed a value of ‘2’ to parameter ‘x’ and a value of ‘3’ to parameter ‘y’”, () => {
   expect( add(2, 3) ).toBe(5); // Pass
  });
});

Here we’re writing more thorough tests to cover for any false positives, albeit at the detriment of providing a description of what the expected behaviour of add() is (as per example 1).

Summary
I believe the more tests the better and option 2 (describe the expected result) definitely aligns with a TDD workflow. Although I like how option 1 (describe the expected behaviour) becomes a functional specification and guide to other devs who might review our code.

What’s your opinion, option 1 or option 2 (or perhaps a hybrid of the both)? I’d love to get some feedback.

Thanks

Aucun commentaire:

Enregistrer un commentaire