使用数据获取的反应测试无法解决诺言

问题描述 投票:0回答:1

我参考以下有关在ReactJS.org上进行数据提取的教程,因为我想将其用作我自己的测试的模板。

我使用npm test,它调用react-scripts测试,据我所知,使用jasmine

我按照本教程中的描述创建了user.js和user.test.js。

// user.test.js

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import User from "./user";

let container = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

it("renders user data", async () => {
  const fakeUser = {
    name: "Joni Baez",
    age: "32",
    address: "123, Charming Avenue"
  };

  jest.spyOn(global, "fetch").mockImplementation(() =>
    Promise.resolve({
      json: () => Promise.resolve(fakeUser)
    })
  );

  // Use the asynchronous version of act to apply resolved promises
  await act(async () => {
    render(<User id="123" />, container);
  });

  expect(container.querySelector("summary").textContent).toBe(fakeUser.name);
  expect(container.querySelector("strong").textContent).toBe(fakeUser.age);
  expect(container.textContent).toContain(fakeUser.address);

  // remove the mock to ensure tests are completely isolated
  global.fetch.mockRestore();
});

[运行测试时,我得到Timeout - Async callback was not invoked within the 5000ms timeout specified by jest. setTimeout.Error

出于某种原因,它似乎无法兑现承诺。

我在做什么错?我简直不敢相信本教程是bugged!任何帮助表示赞赏!

javascript reactjs unit-testing asynchronous promise
1个回答
0
投票

现在正在工作。您严格需要react-dom> = 16.9.0

© www.soinside.com 2019 - 2024. All rights reserved.