Parameterized Tests with Jest
In my other blog, we understood what is a parameterized test. Now as part of this article, we’ll try to understand how to do it using Jest. So, let’s write some code to understand how it’s possible.
Option 1:
First of all, we have to add jest-each
package to our devDependencies
. Once we have the dependency then we can start declaring a test method with parameters.
const isPalindrome = require("../utils").isPalindrome;
const each = require("jest-each").default;
describe("isPalindrome", () => {
each([
["madam", true],
["car", false]
]).it("when the input is '%s'", (text, expected) => {
expect(isPalindrome(text)).toBe(expected);
});
});
Option 2:
If you use Jest ≥ 23.x, then you don’t have to install any additional package. Same behaviour can be achieved by in-built method.
describe("isPalindrome", () => {
it.each([
["madam", true],
["car", false]
])("when the input is '%s'", (text, expected) => {
expect(isPalindrome(text)).toBe(expected);
});
});
And that’s it. Now we have a test to validate our isPalindrome
function with two different arguments ( madam
and car
).
Now let’s check the output which will be same for Option 1 and Option 2,
Note: Here we used es5 syntax to import the modules but we can use es6 syntax as well.
Conclusion
That’s all folks! I hope you’ve been able to understand that we can do the parameterized tests using Jest as well. Also as you observed jest-each
package is easy and simple. To know more about jest-each
package, check this out.
There are several npm packages to write parameterized tests. So, feel free to choose a library depends on your testing framework.