![](/img/trans.png)
[英]How to test a className with the Jest and React testing library
[英]How to test redux state update with react testing library and jest
我正在尝试使用 jest 和 react 测试库编写测试,以查看商店是否更新了 state 并且组件内部显示了新的 state。
我有一个像这样的组件:
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 })
}
它似乎不等待 state 更新。
任何帮助深表感谢
谢谢
我想我已经找到了问题所在。
redux-mock-store 库不允许测试 state 更改。 内部组件正在更改“真实”商店 state 而不是模拟商店,但它在渲染时使用的模拟商店 state 不会改变。
在此测试中,我不需要传递与原始商店不同的初始商店,我可以使用没有 mocking 的“真实”商店:
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));
在触发存储操作之后和“期望”之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.