React Native - mocking FormData in unit tests

女生的网名这么多〃 提交于 2019-12-05 05:27:36

This is an old question, but since I've found it in first page at google, here goes what I've done:

at the beginning of my test I added:

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

this will make sure all places that do

const formData = new FormData()

will use my mock.

Of course, I've only mocked the 'append' method, since in my case it was the only thing I needed. The function that I was testing returned the created FormData object and I did this to test if all worked as expected:

const resultFormData = theFunction()
expect(resultFormData.append.mock.calls.sort(sortFunc)).toEqual(expected)

Add the following code to beginning of your test file

global.FormData = require('FormData')

or

have something like this in your package.json

{
    "jest": {
        "preset": "react-native",
        "transformIgnorePatterns": [
          "<rootDir>/node_modules/(?!react-native|tcomb-form-native|ReactUtils|react-native-button)"
        ],
        "automock": false,
        "setupFiles": [
          "./setupJest.js"
        ]
      }
}

Then create a setupJest.js file on same folder as package.json and have following code in it

global.FormData = require('FormData')

So that jest calls the setupJest.js every time jest runs test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!