繁体   English   中英

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

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

我正在使用Jest与Create React App进行测试,并且试图与同步代码一起测试异步函数,并且当同步部分出现错误时,我需要将其抛出。

测试包括在接收错误的参数类型时期望函数抛出。

该函数抛出“无效参数”。 当接收除“ undefined” (不带参数的函数)或“ number”以外的参数类型时。

USER_API是要调用的API URL。

这是函数:

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.";
};

这是测试:

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

我扩展了函数抛出

但是运行测试显示:预期该函数将引发与错误匹配的错误:/ invalid / gi但是它没有引发任何异常。


测试方法正确还是我写的测试不好? 如果不好,我该如何改善?

谢谢。

由于您的getUsers是一个异步函数,因此它返回Promise 因此,为了对其进行测试,您需要执行以下操作:

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

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

测试异步代码的其他方法之一是:

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

您可以在此处获得更多详细信息: 笑话:测试异步代码

暂无
暂无

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

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