I am writing a test case using jest in to test the data returned from a method.The method returns array of non repeating elements.Now i am trying to use expect() in jest to test whether the array returned from the method has only unique elements.
Returned array from method
arr = [ 'Pizza' ,'Burger' , 'HotDogs'] // All elements are unique
Are there any jest matchers like below to check non repeating elements in array ?
expect(arr).toBeUnique()
Or any logic using existing matchers should be done ?
When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things. For additional Jest matchers maintained by the Jest Community check out jest-extended .
expect. assertions(number) will verify that a certain number of assertions are called during a test. Often, this is useful when testing asynchronous code, so as to make sure that assertions in a callback actually got called.
To check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion. We can use the toHaveBeenCalledWith() matcher method to assert the arguments the mocked function has been called with.
Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.
There is no built on the method to check that array has a unique value, but I would suggest doing something like that:
const goods = [ 'Pizza' ,'Burger' , 'HotDogs'];
const isArrayUnique = arr => Array.isArray(arr) && new Set(arr).size === arr.length; // add function to check that array is unique.
expect(isArrayUnique(goods)).toBeTruthy();
You can use expect.extend
to add your own matchers to Jest.
For example:
expect.extend({
toBeDistinct(received) {
const pass = Array.isArray(received) && new Set(received).size === received.length;
if (pass) {
return {
message: () => `expected [${received}] array is unique`,
pass: true,
};
} else {
return {
message: () => `expected [${received}] array is not to unique`,
pass: false,
};
}
},
});
and use it:
const goods = [ 'Pizza' ,'Burger' , 'HotDogs'];
const randomArr = [ 'Pizza' ,'Burger' , 'Pizza'];
expect(goods).toBeDistinct(); // Passed
expect(randomArr).toBeDistinct(); // Failed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With