FormData is not defined in React Jest

I am writing a unit testing code for the React project. I am trying to test one function

//function aa
export const login = (values) => async => (dispatch) => {
  let bodyFormData = new FormData();

  bodyFormData.append('username', values.login);
  bodyFormData.append('password', values.password);
  return await axios({
   method: 'post',
   url: url,
   data: bodyFormData

//aa test
it("Login Action", async () => {
  afterEach(() => {
  const values = {
    login: "aaaaa",
    password: "bbbbb"
  const expectedResult = { type: "LOGIN_PASS" };

  const result = await store.dispatch(login(values));

In the browser, this works ok. but when testing I get below error

ReferenceError: FormData is not defined

I tried to use this module but no luck...

I do not want to just test axios, I need to test full function.

1 answer

  • answered 2020-01-14 01:58 wentjun

    You will need to mock FormData within your unit test, as the FormData web API is not available in the node.js/jsdom environment.

    function FormDataMock() {
      this.append = jest.fn();
    global.FormData = FormDataMock

    If you wish to mock other methods within the FormData global:

    const entries = jest.fn()
    global.FormData = () => ({ entries })