React Js API call Jest Test Case? - javascript

I am trying to write test cases for my API call function and I don't know where is the error that I could not run my test successfully here is the API call function Code and test Cases code.
export async function getUserTest() {
fetch(config.apiUrl.myFleetAPI, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + 'GcGs5OF5TQ50sbjXRXDDtG8APTSa0s'
}
})
.then((response) => {
return response.json();
})
.catch((reject) => console.log(reject));
}
Test Case Code .
import React from 'react';
import { getUserTest } from '../Service/Dashboard/Dashboard';
global.fetch = jest.fn();
const mockAPICall = (option, data) => global.fetch.mockImplementation(() => Promise[option](data));
describe('Car Components component', () => {
describe('when rendered', () => {
it('should call a fetchData function', async () => {
const testData = { current_user: 'Rahul Raj', name: 'Lafarge' };
mockAPICall('resolve', testData);
return getUserTest().then((data) => {
expect(data).toEqual(testData);
});
});
});
});
and here is what I am getting an error when I tried to run the Test Cases.
Car Components component
when rendered
✕ should call a fetchData function (5 ms)
● Car Components component › when rendered › should call a fetchData function
expect(received).toEqual(expected) // deep equality
Expected: {"current_user": "Rahul Raj", "name": "Lafarge"}
Received: undefined
65 | mockAPICall('resolve', testData);
66 | return getUserTest().then((data) => {
> 67 | expect(data).toEqual(testData);
| ^
68 | });
69 | });
70 | });
at src/Test/MainScreen.test.js:67:30
console.log
TypeError: response.json is not a function
at /Users/rahulraj/Documents/Workproject/Vivafront/lafargeClone/src/Service/Dashboard/Dashboard.js:44:29
at processTicksAndRejections (internal/process/task_queues.js:93:5)

There are two problems with your code:
The resolved value of fetch function is Response which has a .json() method, you forgot to mock it.
You forgot to return the promise like return fetch(/.../). This will cause the promise chain in the test case to not wait for the fetch promise to complete, which is why the return result is undefined
E.g.
api.js:
const config = {
apiUrl: {
myFleetAPI: 'http://localhost:3000/api',
},
};
export async function getUserTest() {
return fetch(config.apiUrl.myFleetAPI, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + 'GcGs5OF5TQ50sbjXRXDDtG8APTSa0s',
},
})
.then((response) => {
return response.json();
})
.catch((reject) => console.log(reject));
}
api.test.js:
import { getUserTest } from './api';
describe('68771600', () => {
test('should pass', () => {
const testData = { current_user: 'Rahul Raj', name: 'Lafarge' };
const response = { json: jest.fn().mockResolvedValueOnce(testData) };
global.fetch = jest.fn().mockResolvedValueOnce(response);
return getUserTest().then((data) => {
expect(data).toEqual(testData);
});
});
});
test result:
PASS examples/68771600/api.test.js (9.885 s)
68771600
✓ should pass (3 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 80 | 100 | 66.67 | 80 |
api.js | 80 | 100 | 66.67 | 80 | 18
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.794 s

Related

Jest - Create React App - Axios: test get mocked

I have a axiosInstance.js axios instance:
import axios from "axios"
import { REACT_FE_ACCESS_TOKEN } from "../../constants/constant";
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL,
headers: {
"content-type": "application/json"
},
responseType: "json"
});
axiosInstance.interceptors.request.use((config) => {
const token = localStorage.getItem(REACT_FE_ACCESS_TOKEN);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export { axiosInstance };
I call it from a class:
import { axiosInstance as api } from "./axiosInstance";
export default class ApiCrud {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
fetchItems() {
return api.get(`${this.getBaseUrl()}`).then(result => result.data);
}
getBaseUrl() {
return this.baseUrl;
}
}
I want to do a write test (using Create React App and Jest).
This is the axiosInstance.test.js file, that works:
import { axiosInstance } from "../../../../utils/api/base/axiosInstance";
import { REACT_FE_ACCESS_TOKEN } from "../../../../utils/constants/constant";
const token = "a1.b2.c3";
beforeEach(() => {
localStorage.clear();
});
describe('Test API Instance', () => {
it ('Test request interceptor with token', () => {
localStorage.setItem(REACT_FE_ACCESS_TOKEN, token);
expect(localStorage.getItem(REACT_FE_ACCESS_TOKEN)).toBe(token);
const result = axiosInstance.interceptors.request.handlers[0].fulfilled({ headers: {} });
expect(result.headers).toHaveProperty("Authorization");
});
it ('Test request interceptor without token', () => {
const result = axiosInstance.interceptors.request.handlers[0].fulfilled({ headers: {} });
expect(result.headers).not.toHaveProperty("Authorization");
});
});
This is the apiCrud.test.js
import ApiCrud from "../../../../utils/api/base/ApiCrud";
const mockedGet = {
email: "info#example.com",
}
jest.mock('axios', () => {
return {
create: jest.fn(() => ({
get: jest.fn(() => Promise.resolve({ data: mockedGet })),
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() }
}
}))
}
})
describe('Test API crud', () => {
it ('Test can get base url', () => {
const apiCrud = new ApiCrud('/fake-url');
expect(apiCrud.getBaseUrl()).toBe('/fake-url');
});
it ('Test can fetch items', () => {
const apiCrud = new ApiCrud('/fake-url');
return apiCrud.fetchItems().then(data => {
expect(data).toBe(mockedGet);
})
});
});
But I get
FAIL src/__tests__/utils/api/base/apiCrud.test.js
● Test API crud › Test can fetch items
TypeError: Cannot read property 'then' of undefined
8 |
9 | fetchItems() {
> 10 | return api.get(`${this.getBaseUrl()}`).then(result => result.data);
| ^
11 | }
12 |
13 | getBaseUrl() {
at ApiCrud.fetchItems (src/utils/api/base/ApiCrud.js:10:12)
at Object.<anonymous> (src/__tests__/utils/api/base/apiCrud.test.js:29:20)
So, I think I'm getting wrong with mocking the get for axios, but... How solve?
You are testing ApiCrud class that depends on the ./axiosInstance module. It's simpler to mock direct dependency ./axiosInstance module than indirect
dependency - axios module.
ApiCrud.js:
import { axiosInstance as api } from './axiosInstance';
export default class ApiCrud {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
fetchItems() {
return api.get(`${this.getBaseUrl()}`).then((result) => result.data);
}
getBaseUrl() {
return this.baseUrl;
}
}
ApiCrud.test.js:
import ApiCrud from './ApiCrud';
import { axiosInstance } from './axiosInstance';
const mockedGet = {
email: 'info#example.com',
};
jest.mock('./axiosInstance');
describe('Test API crud', () => {
afterEach(() => {
jest.clearAllMocks();
});
afterAll(() => {
jest.resetAllMocks();
});
it('Test can get base url', () => {
const apiCrud = new ApiCrud('/fake-url');
expect(apiCrud.getBaseUrl()).toBe('/fake-url');
});
it('Test can fetch items', () => {
axiosInstance.get.mockResolvedValueOnce({ data: mockedGet });
const apiCrud = new ApiCrud('/fake-url');
return apiCrud.fetchItems().then((data) => {
expect(data).toBe(mockedGet);
});
});
});
test result:
PASS examples/69531160/ApiCrud.test.js (10.676 s)
Test API crud
✓ Test can get base url (3 ms)
✓ Test can fetch items (1 ms)
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 73.33 | 0 | 80 | 71.43 |
ApiCrud.js | 100 | 100 | 100 | 100 |
axiosInstance.js | 55.56 | 0 | 0 | 55.56 | 13-17
------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 14.978 s

JEST Testing for Axios - transformResponse

I have following axios get code which uses transformResponse
const downloadAttachment = ({attachmentId, id, oId}) => {
return axios.get(`${url}/attachments/file/${attachmentId}/v1`, {
headers: buildHeaders(),
params: getUrlSearchParams({id, oId}),
responseType: 'blob',
timeout: REQUEST_TIMEOUT,
transformResponse: [(data) => ({file: data})],
});
};
I am using JEST for unit testing. I could get unit test passed with following code
it('should call milo with correct arguments', () => {
expect(axios.get).toHaveBeenCalledWith(mockdownloadAttachmentUrl, {
headers: mockHeaders,
params: {
id: 'ABCD',
oId: 'XYZ',
},
responseType: 'blob',
timeout: 5000,
transformResponse: [expect.any(Function)],
});
});
However JEST is not able to complete 100% code coverage and pointing to line transformResponse: [(data) => ({file: data})] in code which is not covered. How to write test to cover this part of code? Please advice.
If you just want to increase coverage and keep it simple, you can use the following way:
You can use .mockImplementationOnce() to mock axios.get() method, then you can get the transformResponse option in your test case. You can test it as usual.
index.ts:
import axios from 'axios';
const url = 'http://localhost:3000/api';
export const downloadAttachment = ({ attachmentId, id, oId }) => {
return axios.get(`${url}/attachments/file/${attachmentId}/v1`, {
responseType: 'blob',
transformResponse: [(data) => ({ file: data })],
});
};
index.test.ts:
import { downloadAttachment } from './';
import axios from 'axios';
describe('66579132', () => {
it('should transform response', async () => {
const mRes = {};
let transformResponse;
jest.spyOn(axios, 'get').mockImplementationOnce((url, options) => {
transformResponse = options!.transformResponse![0];
return Promise.resolve(mRes);
});
await downloadAttachment({ attachmentId: 1, id: 1, oId: 1 });
expect(axios.get).toBeCalled();
// test tranfromResponse
const response = transformResponse('teresa teng');
expect(response).toEqual({ file: 'teresa teng' });
});
});
unit test result:
PASS examples/66579132/index.test.ts
66579132
✓ should transform response (4 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.393 s

fetch-mock-jest .post resolves to {"size":0,"timeout":0}

I am trying to unit test a function which sends a post request then the API returns a json object. I am trying to do this using jest and fetch-mock-jest.
Now instead of the expected payload the tested function receives {"size":0,"timeout":0}
and throws error invalid json response body at reason: Unexpected end of JSON input. Pretty sure there is something basic I don't see. I spent way more time on this without any progress than I'd like to admit.
Edit: I am pretty new to jest and unit testing in general, so if someone has a better suggestion to go about mocking fetch, please tell me.
Test File
import fetchMock from 'fetch-mock-jest'
import {
refreshAccessToken, isTokenExpired
} from '../../../lib/access/AccessToken'
describe('AccessToken Component...', () => {
it('...Refreshes AccessToken', async () => {
const responseBody = { accessToken: taiDeveloperTokenValid } // The payload I want the AccessToken.refreshAccessTokento get
setAccessToken(taiDeveloperTokenExpired)
process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL = 'http://new-api.com'
fetchMock.post(
`${process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL}/refreshToken`,
new Promise((res) =>
setTimeout(
() =>
res({
status: 200,
body: JSON.stringify(responseBody),
statusText: 'OK',
headers: { 'Content-Type': 'application/json' },
}),
50,
),
),
)
const refreshAccessTokenResponse = await refreshAccessToken()
expect(refreshAccessTokenResponse).toBe(true)
expect(isTokenExpired()).toBe(false)
})
}
Function I am testing
import fetch from 'isomorphic-unfetch'
export const refreshAccessToken = async (): Promise<boolean> => {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL}/refreshToken`,
{
method: 'POST',
credentials: 'include',
},
)
console.log(JSON.stringify(await response)) // this prints {"size":0,"timeout":0}
const data = await response.json()
accessToken = data.accessToken
return true
} catch (error) {
console.log(error) // this prints FetchError { message: 'invalid json response body at reason: Unexpected end of JSON input', type: 'invalid-json'
return false
}
}
You can use jest.mock(moduleName, factory, options) to mock isomorphic-unfetch module by yourself. Don't need fetch-mock-jest module.
E.g.
main.ts:
import fetch from 'isomorphic-unfetch';
export const refreshAccessToken = async (): Promise<boolean> => {
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL}/refreshToken`, {
method: 'POST',
credentials: 'include',
});
const data = await response.json();
const accessToken = data.accessToken;
console.log(accessToken);
return true;
} catch (error) {
console.log(error);
return false;
}
};
main.test.ts:
import { refreshAccessToken } from './main';
import fetch from 'isomorphic-unfetch';
import { mocked } from 'ts-jest/utils';
jest.mock('isomorphic-unfetch');
const fetchMocked = mocked(fetch);
describe('66009798', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should get access token', async () => {
process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL = 'http://new-api.com';
const data = { accessToken: '123' };
const mResponse = { json: jest.fn().mockResolvedValueOnce(data) };
fetchMocked.mockResolvedValueOnce(mResponse as any);
const actual = await refreshAccessToken();
expect(actual).toBeTruthy();
expect(fetch).toBeCalledWith('http://new-api.com/refreshToken', {
method: 'POST',
credentials: 'include',
});
expect(mResponse.json).toBeCalledTimes(1);
});
});
unit test result:
PASS examples/66009798/main.test.ts (13.604 s)
66009798
√ should get access token (37 ms)
console.log
123
at examples/66009798/main.ts:11:13
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 83.33 | 100 | 100 | 80 |
main.ts | 83.33 | 100 | 100 | 80 | 14-15
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.989 s

Jest mock private method in then()

export const get = () => {
return fetch().then((response) => funcA(response));
};
const funcA = (response) => {
if (!response.ok) {
return response.json().then((data) => {
throw Error(...);
});
}
};
How can i mock response.json().then() ? I got the error response.json(...).then is not a function.
I put the json() in the response i mocked
response = { ok: false, json: () => err };
response.json method should return a promise. E.g.
index.ts:
export const funcA = (response) => {
if (!response.ok) {
return response.json().then((data) => {
throw Error(data);
});
}
};
index.test.ts:
import { funcA } from './';
describe('48916842', () => {
it('should pass', () => {
const mResponse = { ok: false, json: jest.fn().mockRejectedValueOnce('custom error') };
expect(funcA(mResponse)).rejects.toThrowError('custom error');
});
});
unit test result with coverage report:
PASS stackoverflow/48916842/index.test.ts (10.276s)
48916842
✓ should pass (5ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 75 | 50 | 50 | 75 |
index.ts | 75 | 50 | 50 | 75 | 4
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.929s, estimated 12s

Asserting that method has been called in a promise with Mocha and Sinon

I have the following simplified method and test, where I want to test that handleResponse() has been called.
The test fails with handleResponse() not beeing called at all. If I modify the code to run handleResponse outside the promise, the test completes successfully.
Is this because the promise is async, and the assertion is being run before the promise? If so, how can I wait for the promise to the completed before running the assertion?
Code:
export function fetchList(id) {
// handleResponse(response); // Works here
return (dispatch) => {
service.getList(id).then((response) => {
handleResponse(response); // Doesnt work here
}, (error) => {
addNotification(error);
});
};
}
Test:
describe('fetchList', () => {
let getListStub;
let handleResponseStub;
beforeEach(() => {
getListStub = sinon.stub(service, 'getList');
handleResponseStub = sinon.stub(appActions, 'handleResponse');
});
afterEach(() => {
getListStub.restore();
handleResponseStub.restore();
});
it('should dispatch handleResponse on success', () => {
const dispatchStub = sinon.stub();
const id = 1;
const returnValue = 'return value';
getListStub.withArgs(id).resolves(returnValue);
listActions.fetchList(id)(dispatchStub);
sinon.assert.calledOnce(getListStub);
sinon.assert.calledOnce(handleResponseStub); // Fails
});
});
You forget add async/await to your unit test and change to return service.getList(...). Otherwise, the assertion will execute before resolving the promise of service.getList(...).
listActions.ts:
import * as service from "./service";
import { handleResponse, addNotification } from "./appActions";
export function fetchList(id) {
return dispatch => {
return service.getList(id).then(
response => {
handleResponse(response);
},
error => {
addNotification(error);
}
);
};
}
appActions.ts:
export function handleResponse(res) {
console.log("handleResponse");
}
export function addNotification(error) {
console.log("addNotification");
}
service.ts:
export function getList(id) {
return new Promise(resolve => {
setTimeout(() => {
resolve([]);
}, 5000);
});
}
listActions.spec.ts:
import * as service from "./service";
import * as appActions from "./appActions";
import * as listActions from "./listActions";
import sinon from "sinon";
describe("fetchList", () => {
let getListStub;
let handleResponseStub;
beforeEach(() => {
getListStub = sinon.stub(service, "getList");
handleResponseStub = sinon.stub(appActions, "handleResponse");
});
afterEach(() => {
getListStub.restore();
handleResponseStub.restore();
});
it("should dispatch handleResponse on success", async () => {
const dispatchStub = sinon.stub();
const id = 1;
const returnValue = "return value";
getListStub.withArgs(id).resolves(returnValue);
await listActions.fetchList(id)(dispatchStub);
sinon.assert.calledOnce(getListStub);
sinon.assert.notCalled(dispatchStub);
sinon.assert.calledOnce(handleResponseStub); // Fails
});
});
Unit test result with coverage report:
fetchList
✓ should dispatch handleResponse on success
1 passing (95ms)
---------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------|----------|----------|----------|----------|-------------------|
All files | 83.33 | 100 | 53.85 | 82.86 | |
appActions.ts | 50 | 100 | 0 | 50 | 2,6 |
listActions.spec.ts | 100 | 100 | 100 | 100 | |
listActions.ts | 85.71 | 100 | 75 | 85.71 | 11 |
service.ts | 25 | 100 | 0 | 25 | 2,3,4 |
---------------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/43186634

Categories

Resources