簡體   English   中英

如何使用 React 測試庫和 jest 測試 redux state 更新

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM