1

I'm trying to test that navigate function is called. I've mocked the component with a jest, but due to the async / promise function it doesn't call the function in time for the test

Component

import React, { useEffect, useState } from 'react';
...
import { Dialog } from '../../../../common/components/Dialog';

const Component = () => {

  ...

  const handleSave= async (value) => {
    const { id } = await newRecord(value);
    navigate(APP_ROUTES.SOMELOCATION(id));
  };

  return (
    <button onClick={() => handleSave(someValue)} />
  );
};

Test

import { navigate } form '@reach/router';
jest.mock('@reach/router');


it('should call navigate when button is clicked', () => {
  wrapper.find('button').simulate('click');
  expect(navigate).toHaveBeenCalled();
});

It does however work if you do: setTimeout(() => { expect(navigate).toHaveBeenCalled() }, 100)

D Clover
  • 45
  • 2
  • 8

2 Answers2

1

After coming across: Stackoverflow: Flush all promises

I added this to my test and it appears to be passing now. So now my test looks like this:

const flushPromises = () => new Promise(setImmediate);


it('should call navigate when button is clicked', async () => {
  wrapper.find('button').simulate('click');
  await flushPromises();
  expect(navigate).toHaveBeenCalled();
});
D Clover
  • 45
  • 2
  • 8
0

I think this happend because mouse click is asynchronous, so you should wait until it ends, try this:

it('should call navigate when button is clicked', async () => {
  await wrapper.find('button').simulate('click');
  expect(navigate).toHaveBeenCalled();
});
I_Shayderov
  • 148
  • 3
  • 9