Reputation: 373
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(() => {
store.clearActions();
});
const values = {
login: "aaaaa",
password: "bbbbb"
};
const expectedResult = { type: "LOGIN_PASS" };
const result = await store.dispatch(login(values));
expect(result).toEqual(expectedResult);
});
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... https://www.npmjs.com/package/form-data
I do not want to just test axios, I need to test full function.
Upvotes: 7
Views: 18583
Reputation: 126
The accepted "global.FormData" mock answer didn't work for me. Typescript doesn't like it and I'm not completely sure of the proper way to handle that single use case. What did work was mocking it in the jest configuration file:
// jest.config.js
const { defaults } = require('jest-config');
module.exports = {
...,
setupFiles: [
'path/to/jest.setup.js',
],
}
And then in the referenced setup file...
// jest.setup.js
Object.defineProperty(window, 'FormData', {
writable: true,
value: jest.fn().mockImplementation(() => ({
append: jest.fn()
}))
})
Upvotes: 0
Reputation: 64
You need to mock the FormData for same, simply add below lines in top of test file.
// @ts-ignore
global.FormData = require('react-native/Libraries/Network/FormData');
Upvotes: 2
Reputation: 545
I was also facing this issue and it turned out that testEnvironment
(inside jest.config.js
) was set to 'node'
. Changing it to 'jsdom'
resolved it.
Upvotes: 4
Reputation: 42556
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 })
Upvotes: 10