Jest mock function in window - javascript

I have a function inside the window that retrieves the axios, from there I make the request for my API. I'm trying to mock her and I can't
window.axios
In my helper:
module.exports = () => window.axios;
In my service:
const axios = require('myHelper')
async myFunc() {
return axios()({
url: `${myURL}/drafts`,
method: 'GET',
});
}
In my test file I try to mock and a console, but it comes as undefined.
const axios = require('helpers/axios');
jest.mock('helpers/axios');
console.log(axios())
I need to axios().get.mockResolvedValue(myMock)

Related

How to test if axios instance is called?

I'm trying to test if the axios instance "myApi" is being called
function code
const myApi = axios.create({
baseURL
})
async function auth () {
const request = await myApi.post('/authorization', {
email,
password
})
return request
}
how can I access the "myApi" instance in the test?

How to mock axios zip download call, using axios-mock-adaptor?

I have a code which is downloading the zip as arraybuffer and subsequently uses admZip to get the files inside. I am trying to unit test a method which calls this method and got stuck around mocking the zip download call.
The code is -
export const downloadZip = async (zipUrl: string): Promise<Buffer> => {
const axiosInstance = axios.create({ headers: getHeaders() });
const body = await axiosInstance.get(zipUrl, {
responseType: 'arraybuffer'
});
return body.data
}
Does anyone have any prior experience on this and can help?
This may help.
const mock = new MockAdapter(axiosInstance);
mock.onGet("https://zip_url").reply(200, {data: "zipData"});
await expect(AxiosClient().get("https://zip_url")).tobe({data: "zipData"})

How can I test vuex action which with jest which has an api call inside it?

ASYNC ACTION VUEX : This is async action which will be called from the
component, it consists of an function fetchGaragesData that will make
an api call to fetch data from server.
[ACTION_TYPES.FETCH_CASHLESS_GARAGES]: async (
{ dispatch, commit, state, rootState },
payload
) => {
commit(MUTATION_TYPES.SET_MISC_KEYS, {
fetchingCashlessGaragesInitiated: true,
})
let { insurerSlug, makeId, rtoCode } = payload
const url = ApiUrls.getCashlessGarages + `${insurerSlug}/${makeId}`
const response = await fetchGaragesData(url, rtoCode)
dispatch(ACTION_TYPES.MODIFY_RTO_WISE_GARAGES_DATA, response)
},
IMPLEMENTATION OF fetchGaragesData: this function internally calls
axios get:
export const fetchGaragesData = (url: string, rtoCode: string) => {
return get(url, {
rto_code: rtoCode,
all_states_data: true,
})
}
How can I test action ACTION_TYPES.FETCH_CASHLESS_GARAGES ???
You might be having API mock response. So, in your spec file you need to add the mock response for that particular API call.
Include your file in spec file which has your actual backend API call.
For example:
import someName from 'path of file'
jest.mock('someName', () => ({
fetchGaragesData: jest.fn((url, rtoCode) =>
success({ body:
Here comes your response body
}})
)
url and rtoCode should be the name of the variables used in your API call file.

How do I mock constructor state initialisation with Jest

New to node.js. I am writing a JS API client that wraps the underlying axios library. In the unit tests I am mocking axios using Jest.
In the constructor of my API class I pass in a URL, and use the axios.create function to create a custom instance of axios and bind it to the the client property.
The problem arises when I mock the axios dependency with jest.mock('axios') - A TypeError is being thrown in the test when an attempt is made to call axios.get:
TypeError: Cannot read property `get` of undefined
I understand why this is happening, but I've not found a way to enable me to mock axios and not have the client field be undefined. Is there a way to get around this, other than injecting axios through the constructor?
Client code and test below:
client.js
jest.mock("axios");
const axios = require("axios");
const mockdata = require("./mockdata");
const ApiClient = require("../../../src/clients/apiclient");
const BASE_URL = "https://www.mock.url.com"
const mockAxiosGetWith = mockResponse => {
axios.get.mockResolvedValue(mockResponse);
};
test("should make one get request", async () => {
mockAxiosGetWith(MOCK_RESPONSE)
// the client field in apiclient is undefined
// due to the jest module mocking of axios
const apiclient = new ApiClient.AsyncClient(BASE_URL);
// TypeError: Cannot read property `get` of undefined
return await apiclient.get("something").then(response => {
expect(axios.get).toHaveBeenCalledTimes(1);
});
});
client.test.js
const axios = require("axios");
const getClient = (baseUrl = null) => {
const options = {
baseURL: baseUrl
};
const client = axios.create(options);
return client;
};
module.exports = {
AsyncClient: class ApiClient {
constructor(baseUrl = null) {
this.client = getClient(baseUrl);
}
get(url, conf = {}) {
return this.client
.get(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
}
};
You need to mock axios so it will return an object which holds the create function which should return the object with the get
import axios from 'axios'
jest.mock('axios', () => ({create: jest.fn()}))
test("should make one get request", async () => {
const get = jest.fn(()=>Promise.resolve(MOCK_RESPONSE))
axios.create.mockImplementation(()=>({get}))
const apiclient = new ApiClient.AsyncClient(BASE_URL);
await apiclient.get("something")
expect(get).toHaveBeenCalledTimes(1);
});

How to test a public async function inside Class using Jest in a ReactJS/Typescript app

Property 'getUsersTotalPayout` does not exist on type typeof PayoutApi
My Class:
import { bind } from 'decko';
import BaseApi from './Base';
import * as NS from './types';
class PayoutApi extends BaseApi {
#bind
public async getUsersTotalPayout(userId: string): Promise<number> {
const params: NS.IGetUsersTotalPayoutRequest = { userId };
const response = await this.actions.get<{ payout: number }>(
'/api/get-total-payout',
params,
);
return response.data.payout;
}
}
export default PayoutApi;
The test file:
import PayoutApi from './LiquidityPool';
const endpoint = '/api/get-total-payout';
const userId = 'foo';
jest.mock(endpoint, () => ({
getUsersTotalPayout: jest.fn(() => Promise.resolve({ data: { payout: 100.21 } }))
}));
describe('API: getUsersTotalPayout', () => {
it('should make a request when we get images', () => {
// const testApi = new PayoutApi();
expect(PayoutApi.getUsersTotalPayout(userId)).toHaveBeenCalledWith(endpoint, 'GET');
});
});
Getting that error on expect(PayoutApi.getUsersTotalPayout).toHaveBeenCalledWith(endpoint, 'GET');
You are currently trying to call method on the class. Since it is not static you should instantiate object of class first.
let api = new PayoutApi();
expect(api.getUsersTotalPayout(userId).....)
since jest.mock mocks module not endpoint or XHR request your test will try sending live request to /api/get-total-payout. For handling that it's needed to know what XHR wrapper do you use. Say for fetch() there is nice wrapper-mocker and libraries like axios also have their equivalence.
As for test itself. It does not work if you call a method and make expect on its result. It should be running method that must call server and then checking for mocked XHR if it has been called with valid parameters:
api.getUsersTotalPayout(userId);
expect(fetch_or_other_wrapper_for_mocking_xhr.get_last_request_method()).toEqual('get', endpoint, userId)

Categories

Resources