@testing-library/react#waitFor TypeScript Examples

The following examples show how to use @testing-library/react#waitFor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfigureOPNavbar.test.tsx    From one-platform with MIT License 6 votes vote down vote up
describe("ConfigureSSI Page", () => {
  it("should render configure SSI page", () => {
    const { getByText } = render(<ConfigureOPNavbar />);
    const headingElement = getByText(/Configure OPC Base/i);
    expect(headingElement).toBeInTheDocument();
  });

  it("should change active theme", async () => {
    const { container } = render(<ConfigureOPNavbar />);
    let currentActiveImage = container.querySelector("img[active-theme]");
    const navOnlyThemeImage = container.querySelector("#nav-only"); // get the nav-only image button
    expect(currentActiveImage?.getAttribute("active-theme")).toEqual(
      "full-ssi"
    );
    fireEvent.click(navOnlyThemeImage!);

    await waitFor(
      () =>
        // getByRole throws an error if it cannot find an element
        container
          .querySelector("img[active-theme]")!
          .getAttribute("active-theme") === "nav-only"
    );
  });
});
Example #2
Source File: ExperimentPageView.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
test('staging experiment shows correct features enabled in overview', async () => {
  await renderExperimentPageView({ experiment: { status: Status.Staging } }, ExperimentView.Overview)

  await waitFor(() => screen.getByRole('button', { name: /Assign Metric/ }))

  expect(getButtonStates()).toEqual({
    editInWizard: true,
    run: true,
    disable: true,
    generalPanelEdit: false,
    assignMetric: false,
    conclusionEdit: null,
  })
})
Example #3
Source File: paste.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Single value text', async () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  const onChange = jest.fn()

  render(
    <DataSheetGrid
      value={emptyRows}
      onChange={onChange}
      columns={columns}
      ref={ref}
    />
  )

  act(() => ref.current.setActiveCell({ col: 0, row: 1 }))

  paste({ text: 'Jeff' })

  await waitFor(() => expect(onChange).toHaveBeenCalled())

  expect(onChange).toHaveBeenCalledWith(
    [
      { firstName: null, lastName: null },
      { firstName: 'Jeff', lastName: null },
    ],
    [{ type: 'UPDATE', fromRowIndex: 1, toRowIndex: 2 }]
  )

  expect(ref.current.activeCell).toEqual({
    col: 0,
    colId: 'firstName',
    row: 1,
  })
})
Example #4
Source File: DataLastUpdated.test.tsx    From crowdsource-dataplatform with MIT License 6 votes vote down vote up
describe('DataLastUpdated', () => {
  const setup = async () => {
    const url = '/aggregated-json/lastUpdatedAtQuery.json';
    fetchMock
      .doMockOnceIf(url)
      .mockResponseOnce(JSON.stringify([{ timezone: '2021-10-11T13:30:05.744813' }]));

    const renderResult = render(<DataLastUpdated />);

    await waitFor(() => {
      expect(fetchMock).toHaveBeenCalledWith(url);
    });
    return renderResult;
  };

  it('should render snapshot', async () => {
    const { asFragment } = await setup();

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #5
Source File: PropertyNamesSelect.test.tsx    From posthog-foss with MIT License 6 votes vote down vote up
test('Can filter properties by case insensitive substring match', async () => {
    const properties = ['Property A', 'Property B', 'Property C']

    const onChange = jest.fn()

    const { findByRole, queryByRole } = render(
        <Provider>
            <PropertyNamesSelect onChange={onChange} allProperties={properties} />
        </Provider>
    )

    const combo = await findByRole('combobox')
    const summaryText = await within(combo).findByText(/0 of 3/)
    userEvent.click(summaryText)

    await findByRole('checkbox', { name: /Property B/ })
    const searchBox = await findByRole('textbox')
    userEvent.type(searchBox, 'property a')

    await waitFor(() => expect(queryByRole('checkbox', { name: /Property B/ })).toBeNull())
})
Example #6
Source File: SQFormDialog.stories.test.tsx    From SQForm with MIT License 6 votes vote down vote up
it('should not call onClose on `escape` keydown because cancel is not available', async () => {
  render(
    <Default
      isOpen={true}
      onSave={handleSave}
      onClose={handleClose}
      showSecondaryButton={false}
    />
  );

  // fireEvent, not userEvent
  // to confirm the 'key' and 'code' values-- > https://keycode.info/
  // https://testing-library.com/docs/dom-testing-library/api-events/ --> find 'keyboard events'
  fireEvent.keyDown(screen.getByRole('presentation'), {
    key: 'Escape',
    code: 'Escape',
  });

  await waitFor(() => {
    expect(handleClose).not.toHaveBeenCalled();
  });
});
Example #7
Source File: FilterBadge.test.tsx    From hub with Apache License 2.0 6 votes vote down vote up
describe('FilterBadge', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('creates snapshot', () => {
    const { asFragment } = render(<FilterBadge {...defaultProps} />);
    expect(asFragment()).toMatchSnapshot();
  });

  describe('Render', () => {
    it('renders component', () => {
      render(<FilterBadge {...defaultProps} />);

      expect(screen.getByText('Category:')).toBeInTheDocument();
      expect(screen.getByText(/Test/)).toBeInTheDocument();
      expect(screen.getByRole('button', { name: /Remove filter/ })).toBeInTheDocument();
    });

    it('calls onClick prop to click button', async () => {
      render(<FilterBadge {...defaultProps} />);

      const btn = screen.getByRole('button', { name: /Remove filter/ });
      await userEvent.click(btn);

      await waitFor(() => expect(onClickMock).toHaveBeenCalledTimes(1));
    });
  });
});
Example #8
Source File: OpenApiDefinition.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('<OpenApiDefinition />', () => {
  it('renders openapi spec', async () => {
    const definition = `
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Artist API
  license:
    name: MIT
servers:
  - url: http://artist.spotify.net/v1
paths:
  /artists:
    get:
      summary: List all artists
      responses:
        "200": 
          description: Success
    `;
    const { getByText } = await renderInTestApp(
      <OpenApiDefinition definition={definition} />,
    );

    // swagger-ui loads the documentation asynchronously
    await waitFor(() => {
      expect(getByText(/\/artists/i)).toBeInTheDocument();
      expect(getByText(/List all artists/i)).toBeInTheDocument();
    });
  });

  it('renders error if definition is missing', async () => {
    const { getByText } = await renderInTestApp(
      <OpenApiDefinition definition="" />,
    );
    expect(getByText(/No API definition provided/i)).toBeInTheDocument();
  });
});
Example #9
Source File: ExperimentDisableButton.test.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
test('disables an experiment', async () => {
  const experimentReloadRef: React.MutableRefObject<() => void> = { current: jest.fn() }
  const experiment = Fixtures.createExperimentFull()
  const { container } = render(<ExperimentDisableButton {...{ experiment, experimentReloadRef }} />)

  mockedExperimentsApi.changeStatus.mockReset()
  mockedExperimentsApi.changeStatus.mockImplementationOnce(async () => undefined)

  const firstDisableButton = screen.getByRole('button', { name: /Disable/ })

  // First Opening - We cancel
  fireEvent.click(firstDisableButton)

  await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))

  expect(container).toMatchSnapshot()

  const cancelButton = screen.getByRole('button', { name: /Cancel/ })
  fireEvent.click(cancelButton)
  await waitForElementToBeRemoved(cancelButton)

  expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(0)
  expect(experimentReloadRef.current).toHaveBeenCalledTimes(0)

  // Second Opening - We disable
  fireEvent.click(firstDisableButton)

  await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
  const cancelButton2nd = screen.getByRole('button', { name: /Cancel/ })

  const allDisableButtons = screen.getAllByRole('button', { name: /Disable/ })
  allDisableButtons.forEach((button) => fireEvent.click(button))

  await waitForElementToBeRemoved(cancelButton2nd)

  expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(1)
  expect(experimentReloadRef.current).toHaveBeenCalledTimes(1)
  expect(mockedExperimentsApi.changeStatus).toMatchInlineSnapshot(`
    [MockFunction] {
      "calls": Array [
        Array [
          1,
          "disabled",
        ],
      ],
      "results": Array [
        Object {
          "type": "return",
          "value": Promise {},
        },
      ],
    }
  `)
})
Example #10
Source File: paste.test.tsx    From react-datasheet-grid with MIT License 5 votes vote down vote up
test('Single value on multiple rows selection', async () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  const onChange = jest.fn()

  render(
    <DataSheetGrid
      value={emptyRows}
      onChange={onChange}
      columns={columns}
      ref={ref}
    />
  )

  act(() =>
    ref.current.setSelection({
      min: { col: 0, row: 0 },
      max: { col: 1, row: 1 },
    })
  )

  paste({ text: 'Elon' })

  await waitFor(() => expect(onChange).toHaveBeenCalled())

  expect(onChange).toHaveBeenCalledWith(
    [
      { firstName: 'Elon', lastName: null },
      { firstName: 'Elon', lastName: null },
    ],
    [{ type: 'UPDATE', fromRowIndex: 0, toRowIndex: 2 }]
  )

  expect(ref.current.selection).toEqual({
    min: {
      col: 0,
      colId: 'firstName',
      row: 0,
    },
    max: {
      col: 0,
      colId: 'firstName',
      row: 1,
    },
  })
})
Example #11
Source File: SQForm.stories.test.tsx    From SQForm with MIT License 5 votes vote down vote up
describe('Tests for BasicForm', () => {
  it('renders BasicForm and calls alert on submit', async () => {
    render(<BasicForm />);

    userEvent.type(screen.getByLabelText(/first name/i), mockData.firstName);

    const {value: lastNameInputValue} = screen.getByLabelText(
      /last name/i
    ) as HTMLInputElement;
    userEvent.type(screen.getByLabelText(/hobby/i), mockData.hobby);
    userEvent.type(screen.getByLabelText(/age/i), mockData.age.toString());

    userEvent.click(screen.getByRole('button', {name: /state/i}));
    userEvent.click(screen.getByRole('option', {name: /kansas/i}));

    userEvent.click(screen.getByRole('checkbox', {name: /cool/i}));

    userEvent.click(
      within(
        screen.getByRole('group', {
          name: /cat or dog/i,
        })
      ).getByRole('radio', {name: /dog/i})
    );

    const warrantyOptions = screen.getByRole('group', {
      name: /warranty options/i,
    });
    userEvent.click(
      within(warrantyOptions).getByRole('checkbox', {name: /drivetrain/i})
    );
    userEvent.click(
      within(warrantyOptions).getByRole('checkbox', {name: /brakes/i})
    );

    userEvent.click(screen.getByRole('button', {name: /submit/i}));

    await waitFor(() =>
      expect(window.alert).toHaveBeenCalledWith(
        JSON.stringify(
          {
            firstName: mockData.firstName,
            lastName: lastNameInputValue,
            city: '',
            age: mockData.age,
            state: mockData.state,
            tenThousandOptions: '',
            note: '',
            preferredPet: mockData.preferredPet,
            warrantyOptions: mockData.warrantyOptions,
            warrantyOptionsSelectAll: false,
            favoriteColors: [2, 4],
            hobby: mockData.hobby,
            cool: mockData.cool,
            lame: false,
          },
          null,
          2
        )
      )
    );
  });

  it('shows confirmation and resets form', async () => {
    render(<BasicForm />);

    userEvent.type(screen.getByLabelText(/first name/i), mockData.firstName);

    userEvent.click(screen.getByRole('button', {name: /reset/i}));

    await screen.findByText('Reset Form');
    userEvent.click(screen.getByRole('button', {name: /reset/i}));

    await waitForElementToBeRemoved(() => screen.queryByText('Reset Form'));
    const {value: firstNameInputValue} = screen.getByLabelText(
      /first name/i
    ) as HTMLInputElement;
    expect(firstNameInputValue).toBe('');
  });
});
Example #12
Source File: LabelTooltipDecorator.spec.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
describe('LabelTooltipDecorator Component', () => {
  const id = 'my-id-provided';
  const tooltipText = 'This is a tooltip text';
  const tooltipCloseLabel = 'Close';
  describe('LabelTooltipDecorator test suite => ', () => {
    it('render a TextField with default props and initial value and test if a input html tag is used', () => {
      const wrapper = shallow(<LabelTooltipDecorator label="My label" />);
      expect(wrapper.length).toEqual(1);
      expect(wrapper.hasClass('tk-input-group__header')).toBe(true);
    });
    it('should display a label if provided', () => {
      const id = 'textfield-1234567890';
      let wrapper = shallow(<LabelTooltipDecorator/>);
      expect(wrapper.find('label.tk-label').length).toBe(0);
      wrapper = shallow(<LabelTooltipDecorator label="LABEL" htmlFor={id} />);
      expect(wrapper.find('label.tk-label').text()).toEqual('LABEL');
      expect(wrapper.find(`label[htmlFor="${id}"]`)).toHaveLength(1);
    });
    it('should have the style --required if showRequired is provided', () => {
      const wrapper = shallow(
        <LabelTooltipDecorator label="LABEL" showRequired/>
      );
      expect(wrapper.find('label.tk-label--required').length).toBe(1);
    });
    it('should display a tooltip if provided', () => {

      let wrapper = shallow(<LabelTooltipDecorator />);
      expect(wrapper.find('Icon').length).toBe(0);
      wrapper = shallow(
        <LabelTooltipDecorator
          id={id}
          tooltip={tooltipText}
          tooltipCloseLabel={tooltipCloseLabel}
        />
      );
      expect(wrapper.find('Icon').length).toBe(1);
      expect(wrapper.find('Icon').prop('iconName')).toBeDefined();
      expect(wrapper.find('Tooltip').length).toBe(1);
      expect(wrapper.find('Tooltip').prop('id')).toEqual(id);
      expect(wrapper.find('Tooltip').prop('description')).toEqual(tooltipText);
      expect(wrapper.find('Tooltip').prop('closeLabel')).toEqual(
        tooltipCloseLabel
      );
    });
  });
  describe('should open and close the tooltip Component', () => {
    it('should handleClickIcon be triggered', async () => {
      const { getByText } = render(<LabelTooltipDecorator
        id={id}
        tooltip={tooltipText}
        tooltipCloseLabel={tooltipCloseLabel}
      />
      );
      const icon = document.querySelector('i.tk-icon-info-round');
      userEvent.click(icon);
      const description = getByText(tooltipText);
      await waitFor(() => expect(description).toBeTruthy());

      const cta = getByText(tooltipCloseLabel);
      userEvent.click(cta);
      waitForElementToBeRemoved(cta);
    });
  });
});
Example #13
Source File: Connector.spec.tsx    From mqtt-react-hooks with MIT License 5 votes vote down vote up
describe('Connector wrapper', () => {
  beforeAll(() => {
    wrapper = ({ children }) => (
      <Connector brokerUrl={URL} options={options}>
        {children}
      </Connector>
    );
  });

  it('should not connect with mqtt, wrong url', async () => {
    const { result } = renderHook(() => useMqttState(), {
      wrapper: ({ children }) => (
        <Connector
          brokerUrl="mqtt://test.mosqu.org:1884"
          options={{ connectTimeout: 2000 }}
        >
          {children}
        </Connector>
      ),
    });

    await waitFor(() => expect(result.current.connectionStatus).toBe('Offline'));
  });

  it('should connect with mqtt', async () => {
    const { result } = renderHook(() => useMqttState(), {
      wrapper,
    });

    await waitFor(() => expect(result.current.client?.connected).toBe(true));

    expect(result.current.connectionStatus).toBe('Connected');

    await act(async () => {
      result.current.client?.end();
    });
  });

  it('should connect passing props', async () => {
    const { result } = renderHook(() => useMqttState(), {
      wrapper: ({ children }) => (
        <Connector
          brokerUrl={URL}
          options={{ clientId: 'testingMqttUsingProps' }}
        >
          {children}
        </Connector>
      ),
    });

    await waitFor(() => expect(result.current.client?.connected).toBe(true));

    expect(result.current.connectionStatus).toBe('Connected');

    await act(async () => {
      result.current.client?.end();
    });
  });
});
Example #14
Source File: ether-swr-config.test.tsx    From ether-swr with MIT License 5 votes vote down vote up
describe('EtherSWRConfig', () => {
  beforeEach(() => {
    mockUseWeb3React(mockeduseWeb3React)
  })

  it('configures the defaults with subscribe', async () => {
    const initialData = 10
    const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
    const contractInstance = new EventEmitterMock()
    const account = '0x001'
    const amount = 50
    const callback = jest.fn()

    const fetcher = mockFetcher(mockedEthFetcher, initialData)

    mockedContract.mockImplementation(() => contractInstance)

    function Container() {
      const { library, active } = useWeb3React()
      return (
        <EthSWRConfig
          value={{
            dedupingInterval: 0,
            ABIs: new Map(Object.entries({ [contractAddr]: ERC20ABI })),
            web3Provider: library,
            provider: () => new Map()
          }}
        >
          <Page />
        </EthSWRConfig>
      )
    }

    function Page() {
      const { account } = useWeb3React()
      const { data, mutate } = useEtherSWR(
        [contractAddr, 'balanceOf', account],
        {
          // A filter from anyone to me
          subscribe: [
            {
              name: 'Transfer',
              topics: [null, account],
              on: callback.mockImplementation(
                // currentData, all the props from the event
                (data, fromAddress, toAddress, amount, event) => {
                  const update = data + amount
                  mutate(update, false) // optimistic update skip re-fetch
                }
              )
            }
          ]
        }
      )
      return <div>Balance, {data}</div>
    }

    const { container } = render(<Container />)

    await waitFor(() => {
      expect(container.firstChild.textContent).toEqual(
        `Balance, ${initialData}`
      )
      expect(fetcher).toBeCalledWith(contractAddr, 'balanceOf', account)
    })

    const contract = mockedContract()
    act(() => {
      contract.emit('Transfer', null, account, amount, {})
      contract.emit('Transfer', null, account, amount, {})
    })

    await waitFor(() =>
      expect(container.firstChild.textContent).toEqual(
        `Balance, ${initialData + amount * 2}`
      )
    )
  })
})
Example #15
Source File: ButtonCopyToClipboard.test.tsx    From hub with Apache License 2.0 5 votes vote down vote up
describe('ButtonCopyToClipboard', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('creates snapshot', () => {
    const { asFragment } = render(<ButtonCopyToClipboard text="Text to copy" />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('renders tooltip after clicking button', async () => {
    render(<ButtonCopyToClipboard text="Text to copy" />);
    expect(screen.queryByRole('tooltip')).toBeNull();

    const btn = screen.getByRole('button', { name: 'Copy to clipboard' });
    await userEvent.click(btn);

    expect(clipboardWriteTextMock).toHaveBeenCalledTimes(1);
    expect(clipboardWriteTextMock).toHaveBeenCalledWith('Text to copy');

    expect(await screen.findByRole('tooltip')).toBeInTheDocument();
  });

  it('renders light tooltip after clicking button', async () => {
    render(<ButtonCopyToClipboard text="Text to copy" tooltipType="light" />);
    expect(screen.queryByRole('tooltip')).toBeNull();

    const btn = screen.getByRole('button', { name: 'Copy to clipboard' });
    await userEvent.click(btn);

    expect(clipboardWriteTextMock).toHaveBeenCalledTimes(1);
    expect(clipboardWriteTextMock).toHaveBeenCalledWith('Text to copy');

    expect(await screen.findByRole('tooltip')).toBeInTheDocument();
    expect(screen.getByRole('tooltip')).toHaveClass('isLight');
  });

  it('renders tooltip after clicking button when navidator.clipboard is undefined', async () => {
    (navigator as any).clipboard = null;
    render(<ButtonCopyToClipboard text="Text to copy" />);
    expect(screen.queryByRole('tooltip')).toBeNull();

    const btn = screen.getByRole('button', { name: 'Copy to clipboard' });
    await userEvent.click(btn);

    await waitFor(() => expect(copyToClipboardMock).toHaveBeenCalledWith('copy'));
    expect(copyToClipboardMock).toHaveBeenCalledTimes(1);

    expect(await screen.findByRole('tooltip')).toBeInTheDocument();
  });
});
Example #16
Source File: OAuthPendingRequests.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
describe('OAuthPendingRequests', () => {
  it('notifies new observers about current state', async () => {
    const target = new OAuthPendingRequests<string>();
    const next = jest.fn();
    const error = jest.fn();

    const input = new Set(['a', 'b']);
    target.pending().subscribe({ next, error });
    target.request(input);

    await waitFor(() => expect(next).toBeCalledTimes(2));
    expect(next.mock.calls[0][0].scopes).toBeUndefined();
    expect(next.mock.calls[1][0].scopes.toString()).toBe(input.toString());
    expect(error.mock.calls.length).toBe(0);
  });

  it('resolves requests and notifies observers', async () => {
    const target = new OAuthPendingRequests<string>();
    const next = jest.fn();
    const error = jest.fn();

    const request1 = target.request(new Set(['a']));
    const request2 = target.request(new Set(['a']));
    target.pending().subscribe({ next, error });
    target.resolve(new Set(['a']), 'session1');
    target.resolve(new Set(['a']), 'session2');

    await expect(request1).resolves.toBe('session1');
    await expect(request2).resolves.toBe('session1');
    expect(next).toBeCalledTimes(3); // once on subscription, twice on resolve
    expect(error).toBeCalledTimes(0);
  });

  it('can resolve through the observable', async () => {
    const target = new OAuthPendingRequests<string>();
    const next = jest.fn(pendingRequest => pendingRequest.resolve('done'));
    const error = jest.fn();

    const request1 = target.request(new Set(['a']));
    target.pending().subscribe({ next, error });

    await expect(request1).resolves.toBe('done');
    expect(next).toBeCalledTimes(2); // once with data on subscription, once empty after resolution
    expect(error).toBeCalledTimes(0);
  });

  it('rejects requests and notifies observers only once', async () => {
    const target = new OAuthPendingRequests<string>();
    const next = jest.fn();
    const error = jest.fn();
    const rejection = new Error('eek');

    const request1 = target.request(new Set(['a']));
    const request2 = target.request(new Set(['a']));
    target.pending().subscribe({ next, error });
    target.reject(rejection);
    target.resolve(new Set(['a']), 'session');

    await expect(request1).rejects.toBe(rejection);
    await expect(request2).rejects.toBe(rejection);
    expect(next).toBeCalledTimes(3); // once on subscription, once or reject, once on resolve
    expect(error).toBeCalledTimes(0);
  });

  it('can reject through the observable', async () => {
    const target = new OAuthPendingRequests<string>();
    const rejection = new Error('nope');
    const next = jest.fn(pendingRequest => pendingRequest.reject(rejection));
    const error = jest.fn();

    const request1 = target.request(new Set(['a']));
    target.pending().subscribe({ next, error });

    await expect(request1).rejects.toBe(rejection);
    expect(next).toBeCalledTimes(2);
  });
});
Example #17
Source File: ExperimentResults.test.tsx    From abacus with GNU General Public License v2.0 4 votes vote down vote up
test('A/B/n: renders correctly for 1 analysis datapoint, not statistically significant', async () => {
  const experiment = Fixtures.createExperimentFull({
    variations: [
      Fixtures.createVariation({
        variationId: 1,
        name: 'control',
        isDefault: true,
        allocatedPercentage: 40,
      }),
      Fixtures.createVariation({
        variationId: 2,
        name: 'treatment1',
        isDefault: false,
        allocatedPercentage: 40,
      }),
      Fixtures.createVariation({
        variationId: 3,
        name: 'treatment2',
        isDefault: false,
        allocatedPercentage: 20,
      }),
    ],
  })
  const metricEstimates = {
    variations: {
      '1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
      '2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
      '3': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
    },
    diffs: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '1_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '2_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
    ratios: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '2_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
  }
  const { container } = render(
    <ExperimentResults
      analyses={[
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.PpNaive, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.IttPure, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoCrossovers, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoSpammers, metricEstimates }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoSpammersNoCrossovers,
          metricEstimates,
        }),
      ]}
      experiment={experiment}
      metrics={metrics}
    />,
  )

  // Check the table snapshot before expanding any metric.
  expect(container.querySelector('.analysis-latest-results')).toMatchSnapshot()

  // Clicking on metric_1 or metric_2 should have no effect on anything, but metric_3 should render the details.
  fireEvent.click(getByText(container, /metric_1/))
  fireEvent.click(getAllByText(container, /metric_2/)[0])
  fireEvent.click(getByText(container, /metric_3/))
  await waitFor(() => getByText(container, /Last analyzed/), { container })
  expect(container.querySelector('.analysis-latest-results .analysis-detail-panel')).toMatchSnapshot()

  expect(mockedPlot).toMatchSnapshot()
})
Example #18
Source File: Home.spec.tsx    From space-traveling with MIT License 4 votes vote down vote up
describe('Home', () => {
  beforeAll(() => {
    mockedPush.mockImplementation(() => Promise.resolve());
    const MockedRouterContext = RouterContext as React.Context<unknown>;
    RouterWrapper = ({ children }): JSX.Element => {
      return (
        <MockedRouterContext.Provider
          value={{
            push: mockedPush,
          }}
        >
          {children}
        </MockedRouterContext.Provider>
      );
    };

    mockedPrismic.mockReturnValue({
      query: () => {
        return Promise.resolve(mockedQueryReturn);
      },
    });

    mockedFetch.mockImplementation(() => {
      return Promise.resolve({
        json: () =>
          Promise.resolve({
            next_page: null,
            results: [
              {
                uid: 'criando-um-app-cra-do-zero',
                first_publication_date: '2021-03-25T19:27:35+0000',
                data: {
                  title: 'Criando um app CRA do zero',
                  subtitle:
                    'Tudo sobre como criar a sua primeira aplicação utilizando Create React App',
                  author: 'Danilo Vieira',
                },
              },
            ],
          }),
      });
    });
  });

  it('should be able to return prismic posts documents using getStaticProps', async () => {
    const postsPaginationReturn = mockedQueryReturn;

    const getStaticPropsContext: GetStaticPropsContext<ParsedUrlQuery> = {};

    const response = (await getStaticProps(
      getStaticPropsContext
    )) as GetStaticPropsResult;

    expect(response.props.postsPagination).toEqual(postsPaginationReturn);
  });

  it('should be able to render logo', () => {
    const postsPagination = mockedQueryReturn;

    render(<App postsPagination={postsPagination} />);

    screen.getByAltText('logo');
  });

  it('should be able to render posts documents info', () => {
    const postsPagination = mockedQueryReturn;

    render(<App postsPagination={postsPagination} />);

    screen.getByText('Como utilizar Hooks');
    screen.getByText('Pensando em sincronização em vez de ciclos de vida');
    screen.getByText('15 mar 2021');
    screen.getByText('Joseph Oliveira');

    screen.getByText('Criando um app CRA do zero');
    screen.getByText(
      'Tudo sobre como criar a sua primeira aplicação utilizando Create React App'
    );
    screen.getByText('15 mar 2021');
    screen.getByText('Danilo Vieira');
  });

  it('should be able to navigate to post page after a click', () => {
    const postsPagination = mockedQueryReturn;

    render(<App postsPagination={postsPagination} />, {
      wrapper: RouterWrapper,
    });

    const firstPostTitle = screen.getByText('Como utilizar Hooks');
    const secondPostTitle = screen.getByText('Criando um app CRA do zero');

    fireEvent.click(firstPostTitle);
    fireEvent.click(secondPostTitle);

    expect(mockedPush).toHaveBeenNthCalledWith(
      1,
      '/post/como-utilizar-hooks',
      expect.anything(),
      expect.anything()
    );
    expect(mockedPush).toHaveBeenNthCalledWith(
      2,
      '/post/criando-um-app-cra-do-zero',
      expect.anything(),
      expect.anything()
    );
  });

  it('should be able to load more posts if available', async () => {
    const postsPagination = { ...mockedQueryReturn };
    postsPagination.results = [
      {
        uid: 'como-utilizar-hooks',
        first_publication_date: '2021-03-15T19:25:28+0000',
        data: {
          title: 'Como utilizar Hooks',
          subtitle: 'Pensando em sincronização em vez de ciclos de vida',
          author: 'Joseph Oliveira',
        },
      },
    ];

    render(<App postsPagination={postsPagination} />);

    screen.getByText('Como utilizar Hooks');
    const loadMorePostsButton = screen.getByText('Carregar mais posts');

    fireEvent.click(loadMorePostsButton);

    await waitFor(
      () => {
        expect(mockedFetch).toHaveBeenCalled();
      },
      { timeout: 200 }
    );

    screen.getByText('Criando um app CRA do zero');
  });

  it('should not be able to load more posts if not available', async () => {
    const postsPagination = mockedQueryReturn;
    postsPagination.next_page = null;

    render(<App postsPagination={postsPagination} />);

    screen.getByText('Como utilizar Hooks');
    screen.getByText('Criando um app CRA do zero');
    const loadMorePostsButton = screen.queryByText('Carregar mais posts');

    expect(loadMorePostsButton).not.toBeInTheDocument();
  });
});
Example #19
Source File: AsrDashboard.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('AsrDashboard', () => {
  global.document.getElementById = jest.fn().mockImplementation(
    x =>
      x === 'float' && {
        style: {
          width: '50%',
        },
      }
  );

  const setup = async () => {
    fetchMock.doMockIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponse(
      JSON.stringify([
        {
          language: 'English',
          total_contribution_count: 36,
          total_contributions: 0.057,
          total_speakers: 9,
          total_validation_count: 2,
          total_validations: 0.001,
          type: 'text',
        },
      ])
    );
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <AsrDashboard />
      </SWRConfig>
    );
    await screen.findByText('ContributionStats');
    return renderResult;
  };

  it('should contain language selector', async () => {
    await setup();
    expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
  });

  it('changing language from language selector should update stats', async () => {
    await setup();
    expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
    expect(screen.queryByText('languages')).not.toBeInTheDocument();
  });

  it('changing language from language selector should display nodata message when data not available', async () => {
    await setup();
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
    });
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    await waitFor(() => expect(screen.queryByText('noDataMessageDashboard')).not.toBeInTheDocument());
    expect(screen.queryByText('languages')).not.toBeInTheDocument();
  });

  it('changing to language where data not available and clicking contribute now should display change user modal for new user', async () => {
    await setup();
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
    await waitFor(() => expect(screen.getByTestId('ChangeUserForm')).toBeInTheDocument());

    userEvent.click(screen.getByRole('button', { name: 'Close' }));

    await waitForElementToBeRemoved(() => screen.queryByTestId('ChangeUserModal'));
  });

  it('changing to language where data not available and clicking contribute now should redirect for existing user', async () => {
    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(
        () => '{"userName":"abc","motherTongue":"","age":"","gender":"","language":"English","toLanguage":""}'
      );
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'English');
    await setup();
    await waitFor(() => {
      expect(localStorage.getItem).toBeCalled();
    });
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
    await waitFor(() => expect(screen.queryByTestId('ChangeUserModal')).not.toBeInTheDocument());
  });
});
Example #20
Source File: SQFormAsyncAutocomplete.stories.test.tsx    From SQForm with MIT License 4 votes vote down vote up
describe('SQFormAsyncAutocomplete Tests', () => {
  describe('AsyncAutocomplete Only', () => {
    it('should render a dropdown, title, and button', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const label = screen.getByText(/async autocomplete/i);
      expect(label).toBeInTheDocument();
      expect(label).toHaveAttribute('id', 'asyncAutocomplete-label');

      const dropdown = screen.getByLabelText(/async autocomplete/i);
      expect(dropdown).toBeInTheDocument();

      const openButton = screen.getByRole('button', {name: /open/i});
      expect(openButton).toBeInTheDocument();
    });

    it('should render with empty initial value', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });

      expect(textField).toHaveTextContent('');
    });

    it('should render with non-empty initial value', () => {
      const sqFormProps = {
        initialValues: {
          asyncAutocomplete: 'fifth',
        },
      };

      render(<SQFormAsyncAutocomplete size="auto" sqFormProps={sqFormProps} />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });
      expect(textField).toHaveValue('Fifth');
    });

    it('should render a list of options when the open button is clicked', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const openButton = screen.getByRole('button', {name: /open/i});

      userEvent.click(openButton);

      const optionsList = screen.getByRole('listbox');
      expect(optionsList).toBeInTheDocument();
      expect(within(optionsList).getAllByRole('option')).toHaveLength(5);
    });

    it('should render a list of options when the user starts typing', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });

      userEvent.type(textField, 'F');

      const optionsList = screen.getByRole('listbox');
      expect(optionsList).toBeInTheDocument();
      expect(within(optionsList).getAllByRole('option')).toHaveLength(3);
    });

    it('should update when an option is selected after typing', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });
      expect(textField).toHaveValue('');

      userEvent.type(textField, 'F');

      const optionToSelect = screen.getByText('Fourth');
      userEvent.click(optionToSelect);

      expect(textField).toHaveValue('Fourth');
    });

    it('should update when an option is selected after clicking the open button', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const openButton = screen.getByRole('button', {name: /open/i});
      userEvent.click(openButton);

      const optionToSelect = screen.getByText('Second');
      userEvent.click(optionToSelect);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });
      expect(textField).toHaveValue('Second');
    });

    it('should clear out value when clear button is clicked', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });
      userEvent.type(textField, 'F');

      const optionToSelect = screen.getByText('Fifth');
      userEvent.click(optionToSelect);
      expect(textField).toHaveValue('Fifth');
      expect(textField).toHaveFocus();

      const clearButton = screen.getByLabelText(/clear/i);
      expect(clearButton).toBeInTheDocument();

      userEvent.click(clearButton);

      expect(textField).toHaveValue('');
    });

    it('should render as disabled when isDisabled is true', () => {
      render(<SQFormAsyncAutocomplete size="auto" isDisabled={true} />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });

      expect(textField).toBeDisabled();
    });

    it(`should display 'No options' when option not in the list is typed`, () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });
      userEvent.type(textField, '2');

      const optionToSelect = screen.getByText('No options');
      expect(optionToSelect).toBeInTheDocument();
    });

    it('should render a loading image when loading is true', () => {
      render(<SQFormAsyncAutocomplete size="auto" loading={true} />);

      const loadingImage = screen.getByRole('progressbar');
      expect(loadingImage).toBeInTheDocument();
    });

    it('should not render a loading image when loading is false', () => {
      render(<SQFormAsyncAutocomplete size="auto" loading={false} />);

      const loadingImage = screen.queryByRole('progressbar');
      expect(loadingImage).not.toBeInTheDocument();
    });
  });

  describe('Autocomplete With Validation', () => {
    it('should render as required when it is a required field', async () => {
      render(<SQFormAsyncAutocompleteWithValidation size="auto" />);

      await waitFor(() => {
        const requiredText = screen.getByText(/required/i);
        expect(requiredText).toBeVisible();
        expect(requiredText).toHaveClass('Mui-required');
      });
    });

    it('should not render as required when it is not a required field', () => {
      render(<SQFormAsyncAutocomplete size="auto" />);

      const requiredText = screen.queryByText(/required/i);
      expect(requiredText).not.toBeInTheDocument();
    });

    it('should highlight field if required but no value selected', async () => {
      render(<SQFormAsyncAutocompleteWithValidation size="auto" />);

      const textField = screen.getByRole('textbox', {
        name: /async autocomplete/i,
      });
      expect(textField).not.toHaveFocus();

      userEvent.tab();
      expect(textField).toHaveFocus();

      userEvent.tab();

      await waitFor(() => {
        const requiredText = screen.getByText(/required/i);
        expect(requiredText).toBeVisible();
        expect(requiredText).toHaveClass('Mui-error');
      });
    });
  });
});
Example #21
Source File: Banner.spec.tsx    From symphony-ui-toolkit with Apache License 2.0 4 votes vote down vote up
describe('Banner', () => {

  const actionMock = jest.fn();
  const closeMock = jest.fn();

  const infoValue = BannerType.INFO;

  it('should render a default banner (neutral, no action, no close)', () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
    }

    const helper = render(<Banner {...props} />);

    expect(helper.getByTestId(props['data-testid'])).toHaveClass(`tk-banner--${infoValue}`);
    expect(helper.getByTestId(props['data-testid'])).toHaveClass('tk-banner--medium');
    expect(helper.getByText(props.content)).toBeInTheDocument();
    expect(helper.container.querySelector('[class*="tk-banner__action"]')).not.toBeInTheDocument();
    expect(helper.container.querySelector('[class*="tk-banner__close"]')).not.toBeInTheDocument();

  });

  it('should not render if show is false', () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
      show: false,
    }

    const helper = render(<Banner {...props} />);

    expect(helper.queryByTestId(props['data-testid'])).not.toBeInTheDocument();
    expect(helper.queryByText(props.content)).not.toBeInTheDocument();

  });

  it('should render the action button if provided', () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
      actionText: 'anAction',
      onAction: actionMock,
    }

    const helper = render(<Banner {...props} />);

    expect(helper.getByText(props.actionText)).toBeInTheDocument();

  });

  it('should call the action handler on action clicked', async () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
      actionText: 'anAction',
      onAction: actionMock,
    }

    const helper = render(<Banner {...props} />);

    userEvent.click(helper.getByText(props.actionText));

    await waitFor(() => {
      expect(actionMock).toHaveBeenCalledTimes(1);
    });

  });

  it('should render the close button if isClosable', () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
      isClosable: true,
      onClose: closeMock,
    }

    const helper = render(<Banner {...props} />);

    expect(helper.container.querySelector('[class*="tk-banner__close"]')).toBeInTheDocument();

  });

  it('should call the close handler on close clicked', async () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
      isClosable: true,
      onClose: closeMock,
    }

    const helper = render(<Banner {...props} />);

    userEvent.click(helper.container.querySelector('[class*="tk-banner__close"]'));

    await waitFor(() => {
      expect(closeMock).toHaveBeenCalledTimes(1);
    });

  });

  it('should apply a classname if provided', () => {

    const props = {
      'data-testid': 'banner',
      content: 'aContent',
      className: 'aClassName'
    }

    const helper = render(<Banner {...props} />);

    expect(helper.getByTestId(props['data-testid'])).toHaveClass(props.className);
  });

  it.each(Object.values(BannerType))(
    'should render the variant "%s"',
    (variant: BannerType) => {

      const props = {
        'data-testid': 'banner',
        content: 'aContent',
        variant,
      }

      const helper = render(<Banner {...props} />);

      expect(helper.getByTestId(props['data-testid'])).toHaveClass(`tk-banner--${variant}`);
    }
  )
});
Example #22
Source File: carousel.spec.tsx    From react-carousel with MIT License 4 votes vote down vote up
describe('<Carousel />', () => {
	let mockGetPageX: jest.SpyInstance<
		number,
		[React.TouchEvent<Element> | React.MouseEvent<Element, globalThis.MouseEvent>]
	>;

	afterEach(() => {
		mockGetPageX.mockRestore();
		jest.clearAllTimers();
		jest.resetAllMocks();
		cleanup();
	});

	beforeEach(() => {
		Element.prototype.getBoundingClientRect = jest.fn(() => {
			return {
				width: 900,
				height: 600,
				top: 0,
				left: 0,
				bottom: 0,
				right: 0,
				x: 0,
				y: 0,
				toJSON: jest.fn(),
			};
		});
		jest.useFakeTimers();
		mockGetPageX = jest
			.spyOn(helpers, 'getPageX')
			.mockImplementation((_: MouseEvent) => 600);
	});

	it('should render right layout', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={false}
				children={carouselItemNodes(6)}
			/>,
		);
		const carousel = getByTestId('carousel');

		expect(carousel.firstChild);
		expect(carousel.firstChild!.firstChild).toBeTruthy();
		expect(carousel.firstChild!.firstChild!.firstChild).toBeTruthy();
		expect(carousel.firstChild!.firstChild!.firstChild).toBeTruthy();
	});

	it('should transform when pressing arrow keys', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				children={carouselItemNodes(6)}
				useArrowKeys={true}
			/>,
		);
		const carousel = getByTestId('carousel');

		fireEvent.click(carousel);
		fireEvent.keyDown(carousel, { keyCode: 39 });
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it("shouldn't listen keyboard event if useArrowKeys option false", async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				children={carouselItemNodes(6)}
				useArrowKeys={false}
			/>,
		);
		const carousel = getByTestId('carousel');

		fireEvent.click(carousel);
		fireEvent.keyDown(carousel, { keyCode: 39 });

		expect(setTimeout).toHaveBeenCalledTimes(0);
	});

	it("shouldn't slide to left if carousel not infinite and shows first item", async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={false}
				useArrowKeys={true}
				children={carouselItemNodes(4)}
			/>,
		);
		const carousel = getByTestId('carousel');

		fireEvent.click(carousel);
		fireEvent.keyDown(carousel, { keyCode: 37 });

		expect(setTimeout).toHaveBeenCalledTimes(0);
	});

	it("shouldn't do anything if press a key that different from arrow keys", async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={false}
				useArrowKeys={true}
				children={carouselItemNodes(4)}
			/>,
		);
		const carousel = getByTestId('carousel');

		fireEvent.click(carousel);
		fireEvent.keyDown(carousel, { keyCode: 317 });

		expect(setTimeout).toHaveBeenCalledTimes(0);
	});

	it('should slide to left when click left button', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={true}
				children={carouselItemNodes(4)}
			/>,
		);
		const carousel = getByTestId('carousel');
		const button = carousel.querySelector('button');

		expect(button).not.toBeNull();

		fireEvent.click(button!);
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it('should slide to right when click right button', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={true}
				children={carouselItemNodes(4)}
			/>,
		);
		const carousel = getByTestId('carousel');
		const button = carousel.querySelectorAll('button')[1];

		expect(button).not.toBeNull();

		fireEvent.click(button!);
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it('should slide back when swiping is done', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={true}
				swiping={true}
				children={carouselItemNodes(12)}
			/>,
		);
		const trackList = getByTestId('trackList');

		mockGetPageX = jest
			.spyOn(helpers, 'getPageX')
			.mockImplementation((_: MouseEvent) => 600);

		fireEvent.mouseDown(trackList, { pageX: 600 });

		mockGetPageX = jest
			.spyOn(helpers, 'getPageX')
			.mockImplementation((_: MouseEvent) => 390);

		fireEvent.mouseMove(trackList, { pageX: 390 });
		fireEvent.mouseUp(trackList, { pageX: 390 });
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it('should slide back when swiping is done and drag size less than item size', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={true}
				swiping={true}
				show={5}
				children={carouselItemNodes(10)}
			/>,
		);
		const trackList = getByTestId('trackList');

		mockGetPageX = jest
			.spyOn(helpers, 'getPageX')
			.mockImplementation((_: MouseEvent) => 600);

		fireEvent.mouseDown(trackList, { pageX: 600 });

		mockGetPageX = jest
			.spyOn(helpers, 'getPageX')
			.mockImplementation((_: MouseEvent) => 190);

		fireEvent.mouseMove(trackList, { pageX: 190 });
		fireEvent.mouseUp(trackList, { pageX: 190 });
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it("shouldn't rotate items if carousel is not infinite", async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={false}
				children={carouselItemNodes(10)}
			/>,
		);
		const carousel = getByTestId('carousel');
		const button = carousel.querySelector('button');

		expect(button).not.toBeNull();

		fireEvent.click(button!);
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it('should rotate items if carousel is infinite', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={true}
				children={carouselItemNodes(10)}
			/>,
		);
		const carousel = getByTestId('carousel');
		const button = carousel.querySelector('button');

		expect(button).not.toBeNull();

		fireEvent.click(button!);
		jest.runAllTimers();

		expect(setTimeout).toHaveBeenCalledTimes(1);
		expect(setTimeout).toHaveBeenLastCalledWith(
			expect.any(Function),
			defaultProps.transition * 1000,
		);
	});

	it('should render stateful items when dynamic prop is true', async () => {
		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				dynamic={true}
				infinite={true}
				children={dynamicCarouselItemNodes()}
			/>,
		);

		const carousel = getByTestId('trackList');
		const button = carousel.querySelector('button');

		expect(button).not.toBeNull();

		fireEvent.click(button!);

		expect(button!.innerHTML).toEqual('1');
	});

	it('should slide to right when click right button', async () => {
		const paginationCallback = jest.fn();
		const mockUsePrevious = jest
			.spyOn(hooks, 'usePrevious')
			.mockImplementation(() => carouselItemNodes(2));

		const { getByTestId } = render(
			<Carousel
				{...defaultProps}
				infinite={true}
				children={carouselItemNodes(4)}
				pageCount={2}
				paginationCallback={paginationCallback}
			/>,
		);
		const carousel = getByTestId('carousel');
		const button = carousel.querySelectorAll('button')[1];

		expect(button).not.toBeNull();

		fireEvent.click(button!);
		jest.runAllTimers();

		expect(paginationCallback).toHaveBeenCalledTimes(1);
		expect(mockUsePrevious).toBeCalled();
	});

	it('should render custom arrows when prop is passed', async () => {
		const { container } = render(
			<Carousel
				{...defaultProps}
				leftArrow={<div className="left-arrow" />}
				rightArrow={<div className="right-arrow" />}
				children={carouselItemNodes(6)}
			/>,
		);

		expect(container.getElementsByClassName('left-arrow')[0]).toBeTruthy();
		expect(container.getElementsByClassName('right-arrow')[0]).toBeTruthy();
	});

	it('should auto swipe in given time period', async () => {
		jest.useFakeTimers();
		const { getAllByText } = render(
			<Carousel
				{...defaultProps}
				autoSwipe={2000}
				show={1}
				slide={1}
				leftArrow={<div className="left-arrow" />}
				rightArrow={<div className="right-arrow" />}
				children={carouselItemNodes(2)}
			/>,
		);

		expect(getAllByText('2').length).toEqual(2);
		expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 2000);

		jest.advanceTimersByTime(2000);
		jest.advanceTimersByTime(2000);

		await waitFor(() => expect(getAllByText('2').length).toEqual(1), {
			timeout: 5000,
		});
	});

	it('should navigate to right on click to navigation item', async () => {
		const { getAllByText } = render(
			<Carousel
				{...defaultProps}
				navigation={(selected: boolean) => <div>{selected ? 'X' : 'O'}</div>}
				leftArrow={<div className="left-arrow" />}
				rightArrow={<div className="right-arrow" />}
				children={carouselItemNodes(6)}
			/>,
		);

		const navigationButton = getAllByText('O')[3];

		expect(navigationButton).not.toBeNull();

		fireEvent.mouseOver(navigationButton!);
		jest.runAllTimers();
	});

	it('should navigate to left on click to navigation item', async () => {
		const { getByText, getAllByText } = render(
			<Carousel
				{...defaultProps}
				navigation={(selected: boolean) => <div>{selected ? 'X' : 'O'}</div>}
				leftArrow={<div className="left-arrow" />}
				rightArrow={<div className="right-arrow" />}
				children={carouselItemNodes(6)}
			/>,
		);

		const navigationButton = getAllByText('O')[3];

		expect(navigationButton).not.toBeNull();

		fireEvent.mouseOver(navigationButton!);
		jest.runAllTimers();

		const leftButton = getByText('X');

		expect(leftButton).not.toBeNull();

		fireEvent.mouseOver(navigationButton!);
		jest.runAllTimers();
	});
});
Example #23
Source File: useBalanceOf.test.tsx    From ether-swr with MIT License 4 votes vote down vote up
describe('useBalanceOf', () => {
  const account = '0x001'
  const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
  let contractInstance

  beforeEach(() => {
    jest.clearAllMocks()
    mockUseWeb3React(mockeduseWeb3React, { account })
    contractInstance = mockContract(mockedContract)
    contracts.clear()
  })

  it('returns the balanceOf from an owner', async () => {
    const mockData = BigNumber.from(10)
    const fetcher = mockFetcher(mockedEthFetcher, mockData)
    const anotherAccount = '0x003'

    function Page() {
      const { data } = useBalanceOf(contractAddr, anotherAccount)
      if (!data) {
        return <div>Loading</div>
      }
      return <div>Balance, {data.toString()}</div>
    }

    const { container } = render(
      <DefaultContainer contractAddr={contractAddr} fetcher={mockedEthFetcher}>
        <Page />
      </DefaultContainer>
    )

    await waitFor(() => {
      expect(container.firstChild.textContent).toEqual(`Balance, ${mockData}`)
      expect(fetcher).toBeCalledWith(contractAddr, 'balanceOf', anotherAccount)
    })
  })

  it('returns the balanceOf from multiple owners', async () => {
    const mockData = BigNumber.from(10)
    const fetcher = mockFetcher(mockedEthFetcher, [mockData])

    function Page() {
      const { data: balances } = useBalanceOf<BigNumber[]>(contractAddr, [
        account
      ])
      if (!balances) {
        return <div>Loading</div>
      }
      return (
        <>
          {balances.map((balance, index) => {
            return <div key={index}>Balance, {balance.toString()}</div>
          })}
        </>
      )
    }

    const { container } = render(
      <DefaultContainer contractAddr={contractAddr} fetcher={mockedEthFetcher}>
        <Page />
      </DefaultContainer>
    )

    await waitFor(() => {
      expect(container.textContent).toEqual(`Balance, ${mockData}`)
      expect(fetcher).toBeCalledWith(
        JSON.stringify([[contractAddr, 'balanceOf', account]])
      )
    })
  })

  it('returns the balanceOf from multiple contract of the same owner', async () => {
    const anotherAccount = '0x003'
    const mockData = BigNumber.from(10)
    const fetcher = mockFetcher(mockedEthFetcher, [mockData])

    function Page() {
      const { data: balances } = useBalanceOf<BigNumber[]>(
        [contractAddr],
        anotherAccount
      )
      if (!balances) {
        return <div>Loading</div>
      }
      return (
        <>
          {balances.map((balance, index) => {
            return <div key={index}>Balance, {balance.toString()}</div>
          })}
        </>
      )
    }

    const { container } = render(
      <DefaultContainer contractAddr={contractAddr} fetcher={mockedEthFetcher}>
        <Page />
      </DefaultContainer>
    )

    await waitFor(() => {
      expect(container.textContent).toEqual(`Balance, ${mockData}`)
      expect(fetcher).toBeCalledWith(
        JSON.stringify([[contractAddr, 'balanceOf', anotherAccount]])
      )
    })
  })
})
Example #24
Source File: index.test.tsx    From useTable with MIT License 4 votes vote down vote up
describe('useFormTable#basic', () => {
  it('submit(点击查询)', async () => {
    const data = { name: 'ahooks' };

    const TestComponent = () => {
      const { formProps, tableProps } = useFormTable((params) => {
        return service({ dataSource: [{ ...params, name: params.name || data.name }] });
      });

      return (
        <Fragment>
          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>
        </Fragment>
      );
    };

    const { queryByTestId, queryByText } = render(<TestComponent />);

    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('foo', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });
  });

  it('reset(重置)', async () => {
    const data = { name: 'ahooks' };

    const TestComponent = () => {
      const { formProps, tableProps } = useFormTable((params) => {
        return service({ dataSource: [{ ...params, name: params.name || data.name }] });
      });

      return (
        <Fragment>
          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
            <button type="reset">Reset</button>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>
        </Fragment>
      );
    };

    const { queryByTestId, queryByText } = render(<TestComponent />);

    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('foo', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });

    fireEvent.click(queryByText('Reset') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });
  });

  it('table(表格操作)', async () => {
    const data = { name: 'ahooks' };

    const TestComponent = () => {
      const { formProps, tableProps, paginationProps } = useFormTable((params) => {
        return service({ dataSource: [{ ...params, name: params.name || data.name }], total: 25 });
      });

      return (
        <Fragment>
          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
            <button type="reset">Reset</button>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>

          <Pagination {...paginationProps} />
        </Fragment>
      );
    };

    const { queryByTestId, queryByText } = render(<TestComponent />);

    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('foo', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });

    fireEvent.click(queryByText('2') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'bar' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('bar', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'bar' }],
        loading: false,
      });
    });

    fireEvent.click(queryByText('Reset') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });
  });

  it('method(插件能获取从哪里请求的)', async () => {
    const data = { name: 'ahooks' };
    let method = methods.ON_FORM_MOUNT;

    const usePlugin = () => {
      return {
        middlewares: (ctx, next) => {
          expect(ctx.meta.queryFrom).toEqual(method);
          return next();
        },
      };
    };

    const TestComponent = () => {
      const { formProps, tableProps } = useFormTable(
        (params) => {
          return service({ dataSource: [{ ...params, name: params.name || data.name }] });
        },
        {
          plugins: [usePlugin()],
        }
      );

      return (
        <Fragment>
          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>
        </Fragment>
      );
    };

    const { queryByTestId, queryByText } = render(<TestComponent />);

    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    method = methods.ON_FORM_SUBMIT;
    await waitFor(() => {
      const element = screen.getByText('foo', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });
  });

  it('actions(暴露出来 actions)', async () => {
    const data = { name: 'ahooks' };
    let $actions = {} as { [name: string]: any };

    const TestComponent = () => {
      const { formProps, tableProps, actions } = useFormTable((params) => {
        return service({ dataSource: [{ ...params, name: params.name || data.name }] });
      });

      $actions = actions;

      return (
        <Fragment>
          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>
        </Fragment>
      );
    };

    const { queryByTestId, queryByText } = render(<TestComponent />);

    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('foo', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'foo' }],
        loading: false,
      });

      const formState = $actions.getFormState();
      expect(formState.values).toEqual({ name: 'foo' });
    });
  });

  it('getFormState(只有点击查询和重置的时候才用到 form 的数据)', async () => {
    const data = { name: 'ahooks' };

    const TestComponent = () => {
      const { formProps, tableProps, paginationProps } = useFormTable((params) => {
        // 加上 total 25,让 pagination 出现分页
        return service({ dataSource: [{ ...params, name: params.name || data.name }], total: 25 });
      });

      return (
        <Fragment>
          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>
          <Pagination {...paginationProps} />
        </Fragment>
      );
    };

    const { queryByTestId, queryByText } = render(<TestComponent />);

    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    // 没有点击查询的时候就点击第二页
    fireEvent.click(queryByText('2') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });
  });

  it('query(点击查询)', async () => {
    const data = { name: 'ahooks' };

    const TestComponent = () => {
      const { formProps, tableProps, paginationProps, query } = useFormTable((params) => {
        // 加上 total 25,让 pagination 出现分页
        return service({ dataSource: [{ ...params, name: params.name || data.name }], total: 25 });
      });

      return (
        <Fragment>
          <button
            onClick={() => {
              query();
            }}
          >
            query
          </button>

          <SchemaForm {...formProps}>
            <Field name={'name'} type="string1" x-props={{ 'data-testid': 'input' }} />
            <button type="submit">Submit</button>
            <FormSpy selector={[]}>
              {({ form }) => {
                return (
                  <button
                    onClick={async () => {
                      try {
                        await form.reset();
                      } catch (e) {
                        // do nothing...
                      }
                    }}
                  >
                    Reset
                  </button>
                );
              }}
            </FormSpy>
          </SchemaForm>

          <div>{JSON.stringify(tableProps)}</div>
          <Pagination {...paginationProps} />
        </Fragment>
      );
    };

    const { queryByText, queryByTestId } = render(<TestComponent />);

    // 第一次是 current 是 1
    await waitFor(() => {
      const element = screen.getByText('ahooks', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20 }],
        loading: false,
      });
    });

    // 没有点击查询的时候就点击第二页
    fireEvent.click(queryByText('2') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });

    fireEvent.click(queryByText('query') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });

    // 重新查询会退到第一页
    fireEvent.change(queryByTestId('input') as HTMLElement, { target: { value: 'foo' } });
    fireEvent.click(queryByText('Submit') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('foo', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });

    // 点击第二页
    fireEvent.click(queryByText('2') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });

    // 重新执行 query()
    fireEvent.click(queryByText('query') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'foo' }],
        loading: false,
      });
    });

    // Reset
    fireEvent.click(queryByText('Reset') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":1', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 1, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });

    // 点击第二页
    fireEvent.click(queryByText('2') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });

    // 重新执行 query()
    fireEvent.click(queryByText('query') as HTMLElement);
    await waitFor(() => {
      const element = screen.getByText('"current":2', { exact: false });
      expect(JSON.parse(element.innerHTML)).toEqual({
        dataSource: [{ ...data, current: 2, pageSize: 20, name: 'ahooks' }],
        loading: false,
      });
    });
  });
});