【问题标题】:How do I re-render a component in Jest?如何在 Jest 中重新渲染组件?
【发布时间】:2022-02-01 16:38:22
【问题描述】:

我有一个 beforeEach() 来呈现我的应用程序:

describe('...', () => {
  beforeEach(() => {
    render(<App />);
  });
  ...
});

我目前正在我的应用程序中进行配置更改。 config 以前是 localStorage 中的布尔值,现在它具有更合适的值,例如 proddev。我的应用在首次加载时会检查旧的布尔值,并将它们更改为各自的非布尔值 - 这是映射:

true -> prod
false -> dev

我正在尝试在 Jest 中为这种转换编写测试。第一个测试背后的想法是设置 localStorage 项,重新渲染应用程序,并检查 localStorage 项是否已正确更新:

it('should show dev config when using old boolean value', () => {
  const toggle = screen.getByTestId('toggle');
  expect(toggle).toBeChecked();
  localStorage.setItem('config', false);

  // re-render app and check localStorage
  render(<App />);
  const toggle2 = screen.getByTestId('toggle');

  expect(toggle2).not.toBeChecked();
  expect(localStorage.getItem('config')).toEqual('dev');
});

但是,这个测试可能会引发错误,可能是因为应用现在被渲染了两次而不是一次:

TestingLibraryElementError: Found multiple elements by: [data-id="toggle"]

如何重新渲染应用程序,使其不会在测试环境中重复?

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    您可以使用 react-testing-library 中的重新渲染功能:https://testing-library.com/docs/marko-testing-library/api/#rerender

    在你的测试中:

    import { ..., rerender } from '@testing-library/react';
    
    it('should show dev config when using old boolean value', () => {
      const toggle = screen.getByTestId('toggle');
      expect(toggle).toBeChecked();
      localStorage.setItem('config', false);
    
      // re-render app and check localStorage
      rerender(<App />);
      const toggle2 = screen.getByTestId('toggle');
    
      expect(toggle2).not.toBeChecked();
      expect(localStorage.getItem('config')).toEqual('dev');
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2020-09-29
      相关资源
      最近更新 更多