React Native-在单元测试中模拟FormData [英] React Native - mocking FormData in unit tests
问题描述
我在测试thunk时遇到问题,因为许多API调用都使用FormData,而且我似乎无法弄清楚如何在测试中对此进行模拟.我正在使用Jest.
I'm having issues testing my thunks, as many of my API calls are using FormData, and I can't seem to figure out how to mock this in tests. I'm using Jest.
我的安装文件如下:
import 'isomorphic-fetch';
// Mocking the global.fetch included in React Native
global.fetch = jest.fn();
// Helper to mock a success response (only once)
fetch.mockResponseSuccess = body => {
fetch.mockImplementationOnce(() =>
Promise.resolve({ json: () => Promise.resolve(JSON.parse(body)) })
);
};
// Helper to mock a failure response (only once)
fetch.mockResponseFailure = error => {
fetch.mockImplementationOnce(() => Promise.reject(error));
};
但是,在所有需要FormData的测试中,我得到以下错误:
However, I get the following error on all tests that require FormData:
ReferenceError: FormData is not defined
我尝试从src/Libraries/Network/FormData
下的react-native-mock
导入FormData文件,但是没有用.
I've tried importing the FormData file from react-native-mock
, under src/Libraries/Network/FormData
, but it didn't work.
所以我想知道是否有人做过运气?
So I was wondering if anyone has had any luck doing this?
通常,我很难确定在React Native中模拟fetch
请求的最佳方法,因此这里的任何建议都是不错的.我尝试了jest-fetch-mock
lib(并打开了一个有关FormData的问题),尝试使用nock
进行设置(没有运气),以及这种简单的Jest实现,但感觉还不对.
In general, I'm having a hard time figuring out the best way to mock fetch
requests in React Native, so any advice here would be nice. I've tried the jest-fetch-mock
lib (and opened an issue about FormData), tried setting up with nock
(no luck), and this plain Jest implementation, but nothing feels right yet.
推荐答案
这是一个古老的问题,但是由于我已经在google的第一页中找到了它,因此请按照以下步骤操作:
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()
将使用我的模拟.
当然,我只嘲笑了'append'方法,因为就我而言,这是我唯一需要的东西.我正在测试的函数返回了创建的FormData对象,我这样做是为了测试所有功能是否均按预期工作:
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)
这篇关于React Native-在单元测试中模拟FormData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!