Here is the unit test solution:
index.tsx
:
import React, { useEffect, useState } from 'react';
export const MyComponent = () => {
const [cntCode, setCntCode] = useState('');
const [country, setCountry] = useState('');
useEffect(() => {
fetch('http://ip-api.com/json')
.then((res) => res.json())
.then((data) => {
setCntCode(data.countryCode);
setCountry(data.country);
});
}, [cntCode, country]);
return (
<div>
country: {country}, cntCode: {cntCode}
</div>
);
};
index.test.ts
:
import { MyComponent } from './';
import React from 'react';
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
describe('MyComponent', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should pass', async () => {
const mResponse = jest.fn().mockResolvedValue({ countryCode: 123, country: 'US' });
(global as any).fetch = jest.fn(() => {
return Promise.resolve({ json: mResponse });
});
const wrapper = mount(<MyComponent></MyComponent>);
expect(wrapper.exists()).toBeTruthy();
expect(wrapper.text()).toBe('country: , cntCode: ');
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
expect(wrapper.text()).toBe('country: US, cntCode: 123');
expect((global as any).fetch).toBeCalledWith('http://ip-api.com/json');
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/59368499/index.test.tsx (9.629s)
MyComponent
✓ should pass (73ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.64s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59368499