2

我在测试时收到有关行为的错误消息。

警告:测试中对EmployeesDashboard 的更新未包含在act(...) 中。

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */


    in EmployeesDashboard (at EmployeesDashboard.test.tsx:69)"

我不知道为什么,因为似乎我已经将所有内容都包装在了行动中……我还应该在这里包装什么?任何帮助将不胜感激,因为我对测试还很陌生。

import React from 'react';
import { mocked } from 'ts-jest/utils';
import { act } from 'react-dom/test-utils';
import { EmployeesDashboard } from '../EmployeesDashboard';
import {
  render,
  wait,
  waitForElementToBeRemoved,
} from '@testing-library/react';

import { Employee } from '@neurocann-ui/types';
import { getAll } from '@neurocann-ui/api';

jest.mock('@neurocann-ui/api');


const fakeEmployees: Employee[] = [
  {
    email: 'joni@gmail.com',
    phone: '720-555-555',
    mailingAddress: {
      type: 'home',
      streetOne: '390 Blake St',
      streetTwo: 'Apt 11',
      city: 'Denver',
      state: 'CO',
      zip: '90203',
    },
    name: 'Joni Baez',
    permissions: ['Employee'],
    hireDate: new Date('2020-09-19T05:13:12.923Z'),
  },
  {
    email: 'joni22@gmail.com',
    phone: '720-555-555',
    mailingAddress: {
      type: 'home',
      streetOne: '390 Blake St',
      streetTwo: 'Apt 11',
      city: 'Denver',
      state: 'CO',
      zip: '90203',
    },
    name: 'Joni Baez',
    permissions: ['Employee'],
    hireDate: new Date('2020-09-19T05:13:12.923Z'),
  },
];

mocked(getAll).mockImplementation(
  (): Promise<any> => {
    return Promise.resolve({ data: fakeEmployees });
  },
);
describe('EmployeesDashboard', () => {
  it('renders progress loader', () => {
    act(() => {
        render(<EmployeesDashboard />)
    });
    const employeesDashboard = document.getElementById(
      'simple-circular-progress',
    );
    expect(employeesDashboard).toBeInTheDocument();
    expect(employeesDashboard).toMatchSnapshot();
  });
  it('renders a table', async () => {
    await act(() => { render(<EmployeesDashboard />) });
    const table = document.getElementById('employees-table');
    expect(table).toBeInTheDocument();
  });
});

4

2 回答 2

0

这通常意味着您需要等待其他内容出现,然后才能期望EmployeesDashboard 出现在文档中。首先等待其他内容,可能是页面的标题或标题。尝试:

it('renders progress loader', async () => {
    
    const {findByText} = render(<EmployeesDashboard />)
    await findByText("something else");
    const employeesDashboard = document.getElementById(
      'simple-circular-progress',
    );
    expect(employeesDashboard).toBeInTheDocument();
    expect(employeesDashboard).toMatchSnapshot();
  });

于 2020-09-30T18:24:13.087 回答
0

尝试在你的模拟中添加一个计时器。

代替:

mocked(getAll).mockImplementation(
  (): Promise<any> => {
    return Promise.resolve({ data: fakeEmployees });
  },
);

尝试:

mocked(getAll).mockImplementation(() => {
  return new Promise(resolve => {
    setTimeout(() => resolve(123), 0);
  });
});
于 2020-09-30T21:04:31.577 回答