【问题标题】:React jest test Promise inside Async在 Async 中反应笑话测试 Promise
【发布时间】:2021-04-25 05:22:55
【问题描述】:

我有下面的代码,但我似乎无法让它工作。我究竟做错了什么?似乎包装承诺的异步导致了这个问题。无论我尝试什么,我总是会出错

export const doLogin = (email, password) => {
  return async (dispatch, getState) => {
    return new Promise((resolve, reject) => {
      resolve(true)
    })
  };
};

and the test using jest and enzyme

expect(await doLogin('', '')).resolves.toEqual(true);

我得到的错误是

    expect(received).resolves.toEqual()

    Matcher error: received value must be a promise

    Received has type:  function
    Received has value: [Function anonymous]

【问题讨论】:

  • doLogin 对我来说没有多大意义。为什么是new Promise?您可以只做async () => true,但该功能似乎过于做作并且失去了上下文。另外,我认为resolves 匹配器已经在等待承诺,而await 明确表示您将true 传递给expect,所以您需要expect(await doLogin()()).toBe(true)

标签: reactjs unit-testing testing jestjs enzyme


【解决方案1】:

doLogin 是返回异步函数的常规函数​​。 await 需要在 expect 调用之外使用,因为 resolves 使断言返回承诺。

应该是:

await expect(doLogin('', '')(dispatchMock, getStateMock)).resolves.toEqual(true);

另外,(dispatch, getState) => ... 函数不会从 async 中受益,因为它只是返回一个承诺而不使用 await 语法。

【讨论】:

    猜你喜欢
    • 2019-01-25
    • 2021-09-27
    • 1970-01-01
    • 2018-10-19
    • 2021-06-17
    • 2018-03-23
    • 2019-07-08
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多