gpt4 book ai didi

javascript - 如何使用 react 测试库和 Jest 测试 redux 状态更新

转载 作者:行者123 更新时间:2023-12-05 00:31:33 34 4
gpt4 key购买 nike

我正在尝试使用 jest 和 react 测试库编写测试,以查看商店是否更新状态并且新状态是否显示在组件内。
我有一个组件,例如:

import { getName } from 'src/store/actions/hello/getName';

const HelloComponent = () => {
const dispatch = useDispatch();
const { name, isLoading } = useSelector((state:RootState) => state.Hello)
useEffect( () => {
dispatch(getName());
}, []);
return (
<div>
{ name &&
Hello {name}
}
</div>
)
}
有一个调用 API 的商店,例如:
const getName = () => (dispatch) => {
const URL = getUrl()
fetch(URL, {method: 'GET'})
.then((response) => response.json())
.then(({ data }) => dispatch({
type: 'SAVE_NAME',
payload: data.name
})) # This action updates the name inside the redux state
};
我正在使用 mswjs 来模拟 API 调用,并且我想在组件挂载后进行测试,DOM 显示“Hello John”。
这是我写的测试,但它不起作用:
it('shows the name', async () => {
const {findByText} = renderWithStore(<HelloComponent />);
expect(await findByText('Hello John')).toBeInTheDocument();
});

renderWithStore 模拟商店。
import configureStore from 'redux-mock-store';
import { render as rtlRender } from '@testing-library/react'
import { initialState as Hello } from '../src/store/reducers/helloReducer';


const mockStore = configureStore()

const initialStateMock = {
Hello
}
function render(
ui
) {
const store = mockStore(initialStateMock);
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return rtlRender(ui, { wrapper: Wrapper })
}
似乎它不等待状态更新。
任何帮助深表感谢
谢谢

最佳答案

我想我找到了问题所在。
redux-mock-store 库不允许测试状态更改。
内部组件正在更改“真实”存储状态,而不是模拟存储状态,但它在渲染时使用模拟存储状态,该状态不会改变。
在这个测试中,我不需要传递与原始存储不同的初始存储,我可以使用“真实”存储而不模拟它:

 import {render} from '@testing-library/react'
import store from 'path_to_the_app_store_obj';

it('shows the name', async () => {
const {findByText} = render(
<Provider store={store}>
<HelloComponent />
</Provider>
);
expect(await findByText('Hello John')).toBeInTheDocument();
});
使用原始商店进行测试。
此外,有时您可能希望等待商店更改,在这些情况下,我发现添加以下内容很有用:
 await act(() => sleep(500));
在触发商店 Action 之后和“预期”之前。

关于javascript - 如何使用 react 测试库和 Jest 测试 redux 状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65698109/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com