首页 > 解决方案 > 如何使用 Jest 和测试库更改组件状态?

问题描述

我正在尝试更改组件的状态以测试更改后的 UI。但我没有运气。

const { getByText } = render(<MyComponent/>);

// Cache original functionality
const realUseState = React.useState;

// Stub the initial state
const stubInitialState = {
  showBrokers: true
};

// Mock useState before rendering your component
await jest
  .spyOn(React, 'useState')
  .mockImplementationOnce(() => realUseState(stubInitialState));

expect(getByText("Brokers")).toBeInTheDocument(); // <<<<---- Here I am getting Customers instead Brokers

标签: reactjsjestjsreact-testing-library

解决方案


您应该能够使用酶的阴影渲染器来加载组件并更改状态。

例如

import React from 'react';
import { shallow } from 'enzyme';
import <yourComponent> from './<yourComponent>';

describe('Testing <yourComponent>', () => {
  it('changes state correctly', () => {
    const renderedComponent = shallow(<<yourComponent> />);

    renderedComponent.setState({ showBrokers: true });

    expect(renderedComponent.state().showBrokers).to.equal(true);
  });
});

以下是一些相关链接:

React & Jest,如何测试更改状态并检查另一个组件

https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/state.html


推荐阅读