Let’s say that I have a test that needs to be run with different sets of data. In the example below, the two tests are actually doing the same thing. The only difference is the data that’s being passed in. In addition, there are essentially two different parameters being passed in to each test: either dataset1 or dataset2, and then there are the values coming from the .each()
call.
const dataset1 = [{ value: 436 }, { value: 89 }]
const dataset2 = [{ value: -72 }, { value: -6 }]
test.each([0.3, 0.6, 0.1])('test with dataset 1', (otherValue) => {
const result = doSomething(otherValue, dataset1)
expect(result).toBeGreaterThan(0)
expect(result).toBeLessThan(1)
})
test.each([-0.5, -0.2, -0.9])('test with dataset 2', (otherValue) => {
const result = doSomething(otherValue, dataset2)
expect(result).toBeGreaterThan(0)
expect(result).toBeLessThan(1)
})
This is a small example, but imagine if I had more than just 2 datasets, maybe up to dataset8, and I also have different values to pass in via .each()
. There’s a part of me that’s looking at this as a DRY (Don’t Repeat Yourself) problem because the logic of each test is exactly the same and perhaps I should look into reducing duplicate code. I’ve considered placing the logic for the test into a function like this:
function testHelper (otherValue, dataset) {
const result = doSomething(otherValue, dataset)
expect(result).toBeGreaterThan(0)
expect(result).toBeLessThan(1)
}
Then I can call this function and pass in different data for each test. I haven’t tried this approach yet. I’m still pretty new to unit testing and am not sure what’s best practice. So I’d like to hear thoughts from the StackOverflow community before proceeding. Thanks