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)

2
  • Where is navigate defined? Commented Feb 1, 2021 at 10:36
  • on line 1: import { navigate } form '@reach/router'; Commented Feb 2, 2021 at 15:03

2 Answers 2

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();
});
Sign up to request clarification or add additional context in comments.

Comments

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();
});

1 Comment

Hi @I_Shayderov unfortunately that didn't work. Although I think that was part of the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.