jest test : Cannot read property 'status' of undefined - javascript

I am trying to test a function with Axios get request. when I get a response I'm calling another function to filter the JSON document.
// sample.js
import axios from "axios";
public async getFruitData{
const response = await axios.get("https://api.url.com/search/fruit", {
params: {
client_id: process.env.REACT_APP_UNSPLASH_TOKEN,
query: term
}
});
return this.filtersResponse(response.data.results); //<---throwing error
};
filterResponse(detailsResponse) {
const excludeFruit = ['apple'];
return detailsResponse.filter(record => !excludeFruit.includes(record.fruit_type));
}
here my jest test
import axios from 'axios';
import Fruit from '../app/fruit';
jest.mock('axios');
test('it filter jsont fruit ', async () => {
mockedAxios.get.mockImplementationOnce(() => Promise.resolve({ data: 'test' }));
const result = await getFruitData();
expect(result).toBe({"data": "test"});
expect(filterResponse(record)).toBeDefined()
});
when I run the test it gave me the following error --> TypeError: Cannot read property 'status' of undefined
How can I test this scenario

Related

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);
});

Unable to use external API on Botpress (axios)

When trying to use axis to query an external Weather API, I get this error
ReferenceError: axios is not defined
at getTropicalCyclones (vm.js:16:9)
Here is my action for getTropicalCyclones {}
(of course I have to hide my client ID and secret)
const getTropicalCyclones = async () => {
const BASE_WEATHER_API = `https://api.aerisapi.com/tropicalcyclones/`
const CLIENT_ID_SECRET = `SECRET`
const BASIN = `currentbasin=wp`
const PLACE = `p=25,115,5,135` // rough coords for PH area of responsibility
const ACTION = `within` // within, closest, search, affects or ''
try {
let text = ''
let response = {}
await axios.get(
`${BASE_WEATHER_API}${ACTION}?${CLIENT_ID_SECRET}&${BASIN}&${PLACE}`
)
.then((resp) => {]
response = resp
text = 'Success retrieving weather!'
})
.catch((error) => {
console.log('!! error', error)
})
const payload = await bp.cms.renderElement(
'builtin_text',
{
text,
},
event.channel
)
await bp.events.replyToEvent(event, payload)
} catch (e) {
// Failed to fetch, this is where ReferenceError: axios is not defined comes from
console.log('!! Error while trying to fetch weather info', e)
const payload = await bp.cms.renderElement(
'builtin_text',
{
text: 'Error while trying to fetch weather info.',
},
event.channel
)
await bp.events.replyToEvent(event, payload)
}
}
return getTropicalCyclones()
So my question is, how do I import axios? I've tried
const axios = require('axios')
or
import axios from 'axios';
but this causes a different error:
Error processing "getTropicalCyclones {}"
Err: An error occurred while executing the action "getTropicalCyclones"
Looking at the package.json on GitHub, it looks like axios is already installed
https://github.com/botpress/botpress/blob/master/package.json
However, I cannot locate this package.json on my bot directory...
Secondly, based on an old version doc it looks like this example code just used axios straight
https://botpress.io/docs/10.31/recipes/apis/
How do I use axios on Botpress?
Any leads would be appreciated
Botpress: v11.0.0
Simply use ES6 import.
include this line at the top of your code.
import axios from 'axios';
Note: I'm expecting that the axios is already installed

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)

Mocking Axios calls using Moxios in order to test API calls

I have the following custom Axios instance:
import axios from 'axios'
export const BASE_URL = 'http://jsonplaceholder.typicode.com'
export default axios.create({
baseURL: BASE_URL
})
With the corresponding service:
import http from './http'
export async function fetchUserPosts(id) {
const reponse = await http.get(`/users/${id}/posts`)
return reponse.data
}
And this is the test for said service:
import moxios from 'moxios'
import sinon from 'sinon'
import http from '#/api/http'
import { fetchUserPosts } from '#/api/usersService'
describe('users service', () => {
beforeEach(() => {
moxios.install(http)
})
afterEach(() => {
moxios.uninstall(http)
})
it('fetches the posts of a given user', (done) => {
const id = 1
const expectedPosts = ['Post1', 'Post2']
moxios.stubRequest(`/users/${id}/posts`, {
status: 200,
response: expectedPosts
})
const onFulfilled = sinon.spy()
fetchUserPosts(1).then(onFulfilled)
moxios.wait(() => {
expect(onFulfilled.getCall(0).args[0].data).toBe(expectedPosts)
done()
})
})
})
Which when executed using Karma + Jasmine raises the following error:
Uncaught TypeError: Cannot read property 'args' of null thrown
What I would like to test is that when the endpoint /users/{id}/posts is hit a mocked response is sent back. All this while using my custom axios instance http.
I've tried stubbing as the first example of the documentation of moxios shows. However I don't think that fits my use case, as I would like to check that the request is formed correctly in my service.
I've also tried with the following code, which works as expected, however I would like to test my service (which the following code does not do):
import axios from 'axios'
import moxios from 'moxios'
import sinon from 'sinon'
describe('users service', () => {
beforeEach(() => {
moxios.install()
})
afterEach(() => {
moxios.uninstall()
})
it('fetches the posts of a given user', (done) => {
const id = 1
const expectedPosts = ['Post1', 'Post2']
moxios.stubRequest(`/users/${id}/posts`, {
status: 200,
response: expectedPosts
})
const onFulfilled = sinon.spy()
axios.get(`/users/${id}/posts`).then(onFulfilled)
moxios.wait(() => {
expect(onFulfilled.getCall(0).args[0].data).toBe(expectedPosts)
done()
})
})
})
Any ideas on how could I fix the error?
I know that is an old question but as I came across with it with the same problem, I'll post my approach:
You don't need to use sinon in this case, as you have an instance of axios, use it to configure moxios (as you already have done)
beforeEach(() => {
moxios.install(http)
})
afterEach(() => {
moxios.uninstall(http)
})
then you test your method like this:
it('test get', async () => {
const expectedPosts = ['Post1', 'Post2']
moxios.wait(() => {
const request = moxios.requests.mostRecent()
request.respondWith({ status: 200, response: expectedPosts }) //mocked response
})
const result = await fetchUserPosts(1)
console.log(result) // ['Post1','Post2']
expect(result).toEqual(expectedPosts)
})
That's it.
Regards

How do I test axios in Jest?

I have this action in React:
export function fetchPosts() {
const request = axios.get(`${WORDPRESS_URL}`);
return {
type: FETCH_POSTS,
payload: request
}
}
How do I test Axios in this case?
Jest has this use case on their site for asynchronous code where they use a mock function, but can I do this with Axios?
Reference: An Async Example
I have done this so far to test that it is returning the correct type:
it('should dispatch actions with the correct type', () => {
store.dispatch(fetchPosts());
let action = store.getActions();
expect(action[0].type).toBe(FETCH_POSTS);
});
How can I pass in mock data and test that it returns?
Without using any other libraries:
import * as axios from "axios";
// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");
// ...
test("good response", () => {
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
// ...
});
test("bad response", () => {
axios.get.mockImplementation(() => Promise.reject({ ... }));
// ...
});
It is possible to specify the response code:
axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));
It is possible to change the mock based on the parameters:
axios.get.mockImplementation((url) => {
if (url === 'www.example.com') {
return Promise.resolve({ data: {...} });
} else {
//...
}
});
Jest v23 introduced some syntactic sugar for mocking Promises:
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
It can be simplified to
axios.get.mockResolvedValue({ data: {...} });
There is also an equivalent for rejected promises: mockRejectedValue.
Further Reading:
Jest mocking documentation
A GitHub discussion that explains about the scope of the jest.mock("axios") line.
A related question which addresses applying the techniques above to Axios request interceptors.
Using jest functions like mockImplementation in TypeScript: Typescript and Jest: Avoiding type errors on mocked functions
I used axios-mock-adapter.
In this case the service is described in ./chatbot.
In the mock adapter you specify what to return when the API endpoint is consumed.
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';
describe('Chatbot', () => {
it('returns data when sendMessage is called', done => {
var mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
chatbot.sendMessage(0, 'any').then(response => {
expect(response).toEqual(data);
done();
});
});
});
You can see it the whole example here:
Service:
https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js
Test:
https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js
I could do that following the steps:
Create a folder __mocks__/ (as pointed by #Januartha comment)
Implement an axios.js mock file
Use my implemented module on test
The mock will happen automatically
Example of the mock module:
module.exports = {
get: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
}),
post: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
if (url === '/something2') {
return Promise.resolve({
data: 'data2'
});
}
}),
create: jest.fn(function () {
return this;
})
};
Look at this
The function to test album.js
const fetchAlbum = function () {
return axios
.get("https://jsonplaceholder.typicode.com/albums/2")
.then((response) => {
return response.data;
});
};
The test album.test.js
const axios = require("axios");
const { fetchAlbum } = require("../utils.js");
jest.mock("axios");
test("mock axios get function", async () => {
expect.assertions(1);
const album = {
userId: 1,
id: 2,
title: "sunt qui excepturi placeat culpa",
};
const payload = { data: album };
// Now mock axios get method
axios.get = jest.fn().mockResolvedValue(payload);
await expect(fetchAlbum()).resolves.toEqual(album);
});
I've done this with nock, like so:
import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'
axios.defaults.adapter = httpAdapter
describe('foo', () => {
it('bar', () => {
nock('https://example.com:443')
.get('/example')
.reply(200, 'some payload')
// test...
})
})
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
File actions.test.js:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: 'test#test.com',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: 'test#test.com',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
New tools for testing have been introduced since the question was initially answered.
The problem with mocking is that you often test the mock and not the real context of your code, leaving some areas of this context untested.
An improvement over telling axios what promise to return is intercepting http requests via Service Workers.
Service worker is a client-side programmable proxy between your web app and the outside world. So instead of mocking promise resolution it is a more broader solution to mock the proxy server itself, intercepting requests to be tested. Since the interception happens on the network level, your application knows nothing about the mocking.
You can use msw (Mock Service Worker) library to do just that. Here is a short video explaining how it works.
The most basic setup I can think of is this:
1️⃣ set up handlers, which are similar to express.js routing methods;
2️⃣ set up mock server and pass handlers as it’s arguments;
3️⃣ configure tests to so that mock server will intercept our requests;
4️⃣ perform tests;
5️⃣ close mock server.
Say you want to test the following feature:
import axios from "axios";
export const fetchPosts = async () => {
const request = await axios.get("/some/endpoint/");
return {
payload: request,
};
};
Then test could look like this:
import { rest } from "msw";
import { setupServer } from "msw/node";
import fetchPosts from "./somewhere";
// handlers are usually saved in separate file(s) in one destined place of the app,
// so that you don't have to search for them when the endpoints have changed
const handlers = [ 1️⃣
rest.get("/some/endpoint/", (req, res, ctx) =>
res(ctx.json({ message: "success" }))
),
];
const server = setupServer(...handlers); 2️⃣
beforeAll(() => {
server.listen(); 3️⃣
});
describe("fetchPosts", () => {
it("should return 'success' message", async () => {
const resp = await fetchPosts();
expect(resp.payload?.data?.message).toEqual("success"); 4️⃣
});
});
afterAll(() => {
server.close(); 5️⃣
});
The configuration may be different depending on framework you are using. Some general examples for, among others, React (both REST and GraphQL) and Angular can be found on MSW’ repo. A Vue example is provided by VueMastery.
You can also find examples on MSW' recipes page.

Categories

Resources