3

When i try to test replace or push i either get empthy object that represents history or when i use mock it is never being called. Currently i get this : Cannot spy the replace property because it is not a function; undefined given instead or when i use mock it dosnt get called.

const submitHandler = async e => {
    e.preventDefault();
    const apiUrl = 'http://localhost:8080/auth/signup'
    const signupData = {
      email,
      password,
      matchPassword,
      username
    }
    const responseData = await postData(apiUrl,signupData,'')
    if (responseData === undefined) {
      toggleValidationErrors([
        {
          param: 'server-error',
          msg: `Server isn't availdable.Please try again later!`
        }
      ]);
    } else if (responseData.validationErrors) {
      toggleValidationErrors(responseData.validationErrors);
    } else {
      history.replace(`/login`);
    }
  };

import React from 'react'

import {render,fireEvent, getByValue,waitForElement} from 'react-testing-library'
import { BrowserRouter } from 'react-router-dom';
import SignupForm from './SignupForm'
describe('<SignupForm />',() => {
    const username = "testUser";
    const email = "testEmail@email.com";
    const password = 'testpass1012'
    const matchPassword = 'testpass1012'
    const history = { replace: jest.fn() };
    const { container, getByPlaceholderText, getByValue,getByText } = render (<SignupForm />,{wrapper:BrowserRouter})
    beforeEach(() => {    

        const submitButton = getByText('SIGN UP')
        fireEvent.click(submitButton)
    })
   
      it('should call history.replace',() => {
          
        const replaceSpy = jest.spyOn(history, 'replace');

          expect(replaceSpy).toBeCalled()
          replaceSpy.mockRestore()
      })
})
Şivā SankĂr
  • 1,757
  • 1
  • 13
  • 28
Ktr1000
  • 223
  • 3
  • 16

1 Answers1

1

The history spy you created would have to get passed into the component you are testing in order for it to get called. The history spy is not being passed in, which is why you are getting undefined.

If your <SignupForm /> component is receiving the history prop, then simply pass in the history spy you created in your test file and it should work.

Another approach would be to create a separate file, say in a util folder and import

import { createBrowserHistory } from 'history';

You have access to this when you install react-router. Then, export the following:

export default createBrowserHistory();

This creates a history object exactly like you get from the react-router history object. From here you could then import the createBrowserHistory object into your test file and make assertions about the history.

Trevor Johnson
  • 370
  • 2
  • 10
  • Both ways dont seem to work.Im getting : Cannot spy the replace property because it is not a function; undefined give n instead. Or : Expected mock function to have been called, but it was not called. – Ktr1000 Mar 31 '19 at 10:52