简体   繁体   English

期望使用带有Create React App(CRA)的Jest的异步函数中的同步代码抛出函数

[英]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. 我正在使用Jest与Create React App进行测试,并且试图与同步代码一起测试异步函数,并且当同步部分出现错误时,我需要将其抛出。

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" . 当接收除“ undefined” (不带参数的函数)或“ number”以外的参数类型时。

The USER_API is the API url to invoke. USER_API是要调用的API URL。

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. 但是运行测试显示:预期该函数将引发与错误匹配的错误:/ invalid / gi但是它没有引发任何异常。


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 . 由于您的getUsers是一个异步函数,因此它返回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 您可以在此处获得更多详细信息: 笑话:测试异步代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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