3

当我尝试测试替换或推送时,我要么得到代表历史的空对象,要么当我使用模拟时,它永远不会被调用。目前我得到这个:无法监视替换属性,因为它不是函数;未定义给定,或者当我使用模拟时它不会被调用。

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

4

1 回答 1

1

您创建的历史间谍必须传递到您正在测试的组件中才能被调用。历史间谍没有被传入,这就是你变得不确定的原因。

如果您的<SignupForm />组件正在接收历史道具,那么只需传入您在测试文件中创建的历史间谍,它应该可以工作。

另一种方法是创建一个单独的文件,例如在 util 文件夹中并导入

import { createBrowserHistory } from 'history';

当您安装 react-router 时,您可以访问它。然后,导出以下内容:

export default createBrowserHistory();

这将创建一个历史对象,就像您从 react-router 历史对象中获得的一样。然后,您可以从这里将createBrowserHistory对象导入您的测试文件,并对历史做出断言。

于 2019-03-31T09:00:17.333 回答