简体   繁体   中英

Expect a function throw for synchronous code inside asynchronous function using Jest with Create React App (CRA)

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.

As your getUsers is an async function, it returns a Promise . So, in order to test it you need to do as follows:

it.only ( "should throw on invalid arguments", () => {
    const str = "hello";
    getUsers ( str ).then ( function ( success ) {

    }, function ( err ) {
        expect ( err ).toBe ( /invalid/gi );
    } );

One of the other ways to test asynchronous code is:

it.only ( "should throw on invalid arguments", () => {
    const str = "hello";
    try {
        await getUsers("hello");
    } catch (e) {
        expect(e).toMatch(/invalid/gi);
    }
});

You can get more details over here: Jest: Testing Asynchronous Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM