Reputation: 1719
I'm testing a axios inside the getArticlesFromDatabase.
Seems like I'm doing wrong, cause console shows following message:
(node:36919) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): here is reject fail:
(node:36919) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
How to fix it?
csrfData.js
import axios from 'axios';
var getArticlesFromDatabase = new Promise(function(resolve, reject) {
axios.get('127.0.0.1:8000/api/articles/get-articles-list').then(response=>{
resolve('herer is resolve success: ',response.data);
}).catch(function (error) {
reject('herer is reject fail: ',error);
});
});
export {getArticlesFromDatabase};
csrfData.test.js
import React from 'react';
import {shallow, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import {expect} from 'chai';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import {getArticlesFromDatabase} from '../components/common/csrfData';
configure({adapter: new Adapter()});
describe('csrfData', function () {
it('csrfData ', function () {
let mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('127.0.0.1:8000/api/articles/get-articles-list').reply(200, data);
getArticlesFromDatabase.then(function(value) {
console.log('getArticlesFromDatabase: ',value);
});
});
});
Upvotes: 1
Views: 10368
Reputation: 2307
Even i struggled a lot for this. But eventually i got the solution.
Here it is:
import { .. } from '../yourServices';
jest.mock('axios');
var axios = require('axios');
//If you use get, post write as below, If you are using axios(config) dont need to mock below
jest.mock('axios', () => ({ post: jest.fn(),create: jest.fn() }));
Then in your tests
describe('Sample Test', () => {
it('Should get - Test', async () => {
const mockedResponse = Promise.resolve({
Response data
});
//Make sure you mock the the functions at import (above) before using here.
//Post case
axios.post.mockResolvedValue(mockedResponse);
//Create Case
axios.create.mockResolvedValue(mockedResponse);
//get ....
//If you use default axios(url, config) or axios(config)
axios.mockResolvedValue(mockedResponse);
//Your code
});
});
Upvotes: 0
Reputation: 3745
There is a adapter plugin which helps in mocking the axios
https://github.com/ctimmerm/axios-mock-adapter
you can also refer my gist if you have generic method which returns the Axios Instance
https://gist.github.com/abhirathore2006/2bdc5e7e696e39e2cbf8b1800e33ecfc
Upvotes: 3