import React, { useState, useEffect, useContext } from 'react'; import {render, act, screen, waitFor, fireEvent} from '@testing-library/react' import { ProfileContextProvider, ProfileContext } from 'context/ProfileContext'; import * as fetchUtil from 'api/fetchUtil'; let profileContext = null; function ProfileView() { const [renderCount, setRenderCount] = useState(0); const profile = useContext(ProfileContext); profileContext = profile; useEffect(() => { setRenderCount(renderCount + 1); }, [profile.state]); return (
{ renderCount } { profile.state.identity?.guid } { profile.state.identity?.handle } { profile.state.identity?.name } { profile.state.identity?.description } { profile.state.identity?.location } { profile.state.identity?.image } { profile.state.identity?.revision } { profile.state.identity?.seal } { profile.state.identity?.version } { profile.state.identity?.node }
); } function ProfileTestApp() { return ( ) } const realFetchWithTimeout = fetchUtil.fetchWithTimeout; const realFetchWithCustomTimeout = fetchUtil.fetchWithCustomTimeout; let identity = { }; beforeEach(() => { const mockFetch = jest.fn().mockImplementation((url, options) => { if (options.method === 'PUT') { identity = JSON.parse(options.body); } return Promise.resolve({ json: () => Promise.resolve(identity) }); }); //@ts-ignore fetchUtil.fetchWithTimeout = mockFetch; //@ts-ignore fetchUtil.fetchWithCustomTimeout = mockFetch; }); afterEach(() => { //@ts-ignore fetchUtil.fetchWithTimeout = realFetchWithTimeout; //@ts-ignore fetchUtil.fetchWithCustomTimeout = realFetchWithCustomTimeout; }); test('testing profile sync', async () => { render(); await waitFor(async () => { expect(profileContext).not.toBe(null); }); await waitFor(async () => { expect(screen.getByTestId('name').textContent).toBe(""); }); await act(async () => { identity = { name: 'jester' }; await profileContext.actions.setToken({ guid: 'abc', server: 'test.org', appToken: '123' }); await profileContext.actions.setRevision(1); }); await waitFor(async () => { expect(screen.getByTestId('name').textContent).toBe("jester"); }); await act(async () => { identity = { name: 'tester' }; await profileContext.actions.setRevision(2); }); await waitFor(async () => { expect(screen.getByTestId('name').textContent).toBe("tester"); }); const count = screen.getByTestId('count').textContent; await act(async () => { identity = { name: 'renderer' }; await profileContext.actions.setRevision(3); }); await waitFor(async () => { const renderCount = parseInt(screen.getByTestId('count').textContent); const nextCount = parseInt(count) + 1; expect(nextCount).toBe(renderCount); }); await act(async () => { await profileContext.actions.clearToken(); }); });