lundi 13 juillet 2020

What's the propper way to test the react ui including an async rest request?

My App fetches some data from a rest api using an instance of axios. Now I have a test that looiks like:

it('api call test', async () => {
    act(() => {
        ReactDOM.render(
            <React.StrictMode>
                <App/>
            </React.StrictMode>
            , container);
    });

    const data = {
        "id": "1",
        "text": "bibabo"
    };

    jest.spyOn(api, "get").mockImplementation((url: string, config: AxiosRequestConfig | undefined) => {
        return Promise.resolve({data});
    })
    const main = document.querySelector("main");
    const link = document.querySelector("a[href='/data/1']");
    act(() => {
        link?.dispatchEvent(new MouseEvent('click', {bubbles: true}));
    });
    await wait(() => {
        expect(main?.textContent).toContain("bibabo");
    });
});

This test works fine, but i'm a little bit unhappy about using await wait especially i'm not sure if this as a case for using wait. So is there a better/propper way to test the ajax request?

Aucun commentaire:

Enregistrer un commentaire