[英]The state is not updated after click in ReactJs
I test my React application using Enzyme and Jest.我使用 Enzyme 和 Jest 测试我的 React 应用程序。 This is my component:
这是我的组件:
function App() { const [state, setState] = React.useState('default'); const [loading, setLoading] = React.useState(false); const [name, setName] = React.useState('ji'); return ( <div className="App"> <h2>{state}</h2> <h1 className='test'>Helljo</h1> <h1 className='test'>Hello</h1> <button onClick={() => { setState('changed'); setLoading(true) }}>Click</button> <Child setName={setName} name={name}/> </div> ); } export default App;
Clicking on the button I update the text in h2
tag.单击按钮我更新
h2
标签中的文本。
Below is my test which should test this event:下面是我的测试,应该测试这个事件:
import { configure, shallow, mount, render } from 'enzyme'; import App from './App'; import React, {useState} from "react"; describe('Test main component', () => { let wrapper = shallow(<App />); let setState; let setName; let setLoading; beforeEach(() => { setState = jest.fn(x => {}); setName = jest.fn(x => {}); setLoading = jest.fn(x => {}); React.useState = jest.fn().mockImplementationOnce(state => [state, setState]).mockImplementationOnce(loading => [loading, setLoading]).mockImplementationOnce(name => [name, setName]) }); afterEach(() => { jest.clearAllMocks(); }); test('should change state on text', () => { const btn = wrapper.find("button"); btn.simulate("click"); expect(wrapper.find('h2').text()).toBe('changed'); }) })
Running this test I get:运行这个测试我得到:
Expected: "changed"
Received: "default"
Why do I get this and how to make the test workable?为什么我得到这个以及如何使测试可行? Note: if I remove the
beforeEach
statement the code works as I expect, but I need to keep that logic, because I need to test the state from my component.注意:如果我删除
beforeEach
语句,代码将按预期工作,但我需要保留该逻辑,因为我需要从我的组件测试 state。
Question: Why does my code not retrieve the expected result and how to solve it?问题:为什么我的代码没有检索到预期的结果,如何解决?
Because you mock setState
to a function not do anything so state
will not update.因为你将
setState
模拟为 function 没有做任何事情所以state
不会更新。
setState = jest.fn(x => {});
You can't mock setState
.你不能模拟
setState
。 Because it related to change state
and re-render component logic of component
.因为它涉及更改
state
并重新渲染 component 的component
逻辑。 So you should keep the setState
, focus on another logic.所以你应该保留
setState
,专注于另一个逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.