【问题标题】:Expect a function throw for synchronous code inside asynchronous function using Jest with Create React App (CRA)期望使用 Jest 和 Create React App (CRA) 在异步函数中为同步代码抛出函数
【发布时间】:2019-08-16 23:04:40
【问题描述】:

我正在使用 Jest 通过 Create React App 进行测试,我正在尝试测试一个异步函数以及一个同步代码,我需要它在同步部分出现错误时抛出。

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

函数抛出 "Invalid arguments." 当接收到参数类型不是 "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 但它没有抛出任何东西。


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

谢谢。

【问题讨论】:

  • 我不明白你为什么要这样写这个函数。如果您的计数会限制响应长度,例如使用查询参数,这种预先指定计数的方法会很有趣。在您的情况下,您只是将膨胀添加到简单的提取中,将关注点分成两个不同的函数(提取和切片)会更简单,更容易阅读
  • @BJRINT 感谢您的回复,但我真的不知道什么时候在函数内部或外部进行测试?例如,请查看此链接:codeshare.io/GkyN3x
  • @brian-lives-outdoors 不,我的问题是同步和异步之间的组合,这是诀窍!
  • 这是a duplicate。改变你的函数来抛出一个实际的Error,像这样:throw new Error('Invalid arguments.');,你的测试就变成了expect(getUsers(str)).rejects.toThrow(/invalid/gi);

标签: javascript asynchronous synchronization jestjs


【解决方案1】:

由于您的getUsersasync 函数,因此它是returns a 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);
    }
});

您可以在此处获取更多详细信息:Jest: Testing Asynchronous Code

【讨论】:

  • 你好,它成功了,谢谢你,我的错我在传递一个数字时等待它抛出(这是错误的):p
  • 再次声明,这是duplicate。该函数应该像这样抛出Errorthrow new Error('Invalid arguments.');。那么测试就是:expect(getUsers(str)).rejects.toThrow(/invalid/gi);
猜你喜欢
  • 2020-05-01
  • 2017-12-06
  • 2023-02-08
  • 2022-11-10
  • 2020-08-04
  • 2020-07-09
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
相关资源
最近更新 更多