reactjs - 如何使用 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
解决方案
您应该能够使用酶的阴影渲染器来加载组件并更改状态。
例如
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);
});
});
以下是一些相关链接:
https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/state.html
推荐阅读
- android - 通过 wifi 使用套接字编程 tcp 将 linux 作为客户端(odroid)与作为服务器的 android 应用程序连接
- java - 无法在不重新启动的情况下更改 Windows 中的环境变量
- python - Tensorflow Beamsearch 解码器无法解码值
- java - JPA:将 LocalDateTime 属性与 builder.currentTimestamp() 进行比较
- spring - JWT 与 Angular 和 SpringBoot
- .htaccess - 如何使用 htaccess 重定向查询字符串的多个参数
- php - 在mysql中将变量减1
- sql-server - SQL Server - 在返回数据之前估计查询结果集大小的最佳方法(以 MB 为单位)?
- scala - scala函数接受返回另一个函数的函数
- spring-boot - SpringBoot GraphQL 字段名不匹配