How to mock RNFetchBlob for upload image using jestjs?
Code:
await RNFetchBlob.fetch(
'POST',
'https://www.example.net/api/v1/upload-image',
{
Authorization: 'Bearer token',
'Content-Type': 'application/octet-stream',
},
'base64string',
)
.then(res => res.json())
.then(res => {
setUrl(res.url);
});
You can use jest.mock(moduleName, factory, options) to mock rn-fetch-blob
module. Below is a unit test solution.
E.g.
index.js
:
import RNFetchBlob from 'rn-fetch-blob';
import React, { useState } from 'react';
const UploadComponent = () => {
const [url, setUrl] = useState('');
const upload = async () => {
await RNFetchBlob.fetch(
'POST',
'https://www.example.net/api/v1/upload-image',
{
Authorization: 'Bearer token',
'Content-Type': 'application/octet-stream',
},
'base64string',
)
.then((res) => res.json())
.then((res) => {
setUrl(res.url);
});
};
return (
<div>
<button onClick={upload}>Upload</button>
<span>{url}</span>
</div>
);
};
export default UploadComponent;
index.test.js
:
import UploadComponent from './';
import { shallow } from 'enzyme';
import { act } from 'react-dom/test-utils';
import RNFetchBlob from 'rn-fetch-blob';
jest.mock(
'rn-fetch-blob',
() => {
const mRNFetchBlob = {
fetch: jest.fn(),
};
return mRNFetchBlob;
},
{ virtual: true },
);
const whenStable = async () =>
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
});
describe('60116223', () => {
it('should upload image', async () => {
const mJSON = { url: 'https://www.example.net/api/v1/upload-image' };
const mResponse = { json: jest.fn().mockReturnValueOnce(mJSON) };
RNFetchBlob.fetch.mockResolvedValueOnce(mResponse);
const wrapper = shallow(<UploadComponent></UploadComponent>);
expect(wrapper.find('span').text()).toBe('');
wrapper.find('button').simulate('click');
await whenStable();
expect(wrapper.find('span').text()).toBe(mJSON.url);
});
});
Unit test results with 100% coverage:
PASS stackoverflow/60116223/index.test.js (6.171s)
60116223
✓ should upload image (27ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.194s
Source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60116223