I am using Jest for testing with Create React App and I am trying to test an asynchronous function along with a synchronous code and I need it to throw when the synchronous part has an error.
The test consist on expecting the function to throw when recieving wrong arguments types.
The function throw "Invalid arguments." when receiving arguments type other than "undefined" (function without arguments) or a "number".
The USER_API is the API url to invoke.
Here is the function:
export const getUsers = async (count, ...rest) => {
if (["undefined", "number"].includes(typeof count) && rest.length === 0) {
const response = await fetch(USERS_API);
const users = await response.json();
if (count && typeof count === "number") {
return users.slice(0, count - 1);
}
return users;
}
throw "Invalid arguments.";
};
Here is the test:
it.only("should throw on invalid arguments", () => {
const str = "hello";
expect(() => getUsers(str)).toThrow(/invalid/gi);
});
I expexted the function to throw
But running the test shows: Expected the function to throw an error matching: /invalid/gi But it didn't throw anything.
Is the testing method right or am I writing a bad test? If is it bad how can I improve it?
Thank you.