[英]how can i test browser back-button behaviour using jest and (react-) testing-library?
[英]How do I test my actions, state and UI. I'm using context API with jest and testing-library?
我將 Context 以某種狀態包裹在我的應用程序周圍。 我可以通過我的 useMyState 和 useMyDispatch 鈎子(只是簡化)訪問我的組件中的狀態和調度。 然后我有整個狀態管理發生的胖動作,我的減速器非常瘦。 只是傳播新的有效載荷並返回狀態。 我的動作是這樣的:
async function myAsyncFunction(dispatch: CurrencyDispatch, state: CurrencyState, name: string) {
const thingOne = sompute thing...
const thingTwo = await getThing();
dispatch({
type: ActionTypes.SOME_ACTION,
payload: {
thingOne,
thingTwo,
},
});
}
一些操作發生在應用程序提供程序中,例如在 UI 出現之前獲取和設置一些初始狀態,我正在顯示微調器。 如何測試這些操作並查看全局存儲是否按預期更新?
我正在用jest
和testing-library/react
test('Render with initial state', async () => {
const {getByText, getByTestId} = render(
<Provider>
<MyApp/>
</Provider>
);
await waitForElementToBeRemoved(() => getByTestId('loader'));
expect(getByText('My title')).toBeInTheDOM();
});
測試失敗。 在這里我以 Spinner 結束,因為我的設置初始狀態的應用程序還沒有被調用。
myAsyncFunction
?我不能說這是模擬狀態的正確方法,但這是我的做法:
在這種情況下,如何正確模擬 myAsyncFunction? 使用 jest.mock
jest.mock('../api/myService', () => {
getDataList: () => jest.fn,
}));
如何發送模擬數據?
如何讀取新狀態並測試 UI 是否按預期更新?
只需在測試期間更改 adhoc 上的 store 值,但首先創建一個包裝器:
包裝紙
import MyContext, { defaultState } from './providers/mycontext';
export mockState = defaultState;
interface IMyState {
myState: typeof defaultState.store;
}
const wrapDep = (tree: ReactNode, state?: IMyState) => {
const mState = state?.myState ? state.myState : mockState.store;
return (
<MyContext.Provider value={{...mockState, store: mState}}>
{tree}
</MyContext.Provider>
);
}
測試
describe('MyComponent', () => {
it('should display data', () => {
const { getByText } = render(wrapDep(<MyComponent itemId={''} />, {
myState: {
...mockState.store,
items: mockItems
}
}));
expect(getByText(mockItems[0])).not.toBeNull();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.