I have been trying to write tests to test a axios call but now need to test the catch part.
I have been able to do the then by mocking axios like so but can't seem to get a way to test catch. I have followed many different examples from stack overflow and the web.
jest.mock('axios', () => jest.fn(() => Promise.resolve({ data: mockData })));
but that will always return a good result so can't test the catch. The bit of code I want to test is: goToUrl() is just a window.location.assign(url) but imported.
fetchBundlesFromApi(params)
.then(({ data: { bundles } }) => {
updateBundles(bundles);
this.setState({ showUpdatingPrices: false });
})
.catch(() => goToUrl(bundlesUrl));
In my test for .then() part I do this:
const fetchedBundles = await fetchBundlesFromApi(
'?params',
);
expect(fetchedBundles.data).toEqual(mockData);
However if I follow examples like this one Mocking Axios with Jest in React - mock function not being called I can't manually mock get if I put a mock axios file in a folder __mocks__ then a lot of the test suit fails so I just want to mock it in this one test file.
here is one of the examples I tried doing:
jest.mock('axios', () => ({
get: () => jest.fn(() => Promise.resolve({ data: mockData })),
default: () => jest.fn(() => Promise.resolve({ data: mockData })),
}));
but the tests error with TypeError: (0 , _axios.default) is not a function
EDIT:
Here is my fetchBundlesApi function:
const fetchBundlesFromApi = params => axios(`${bundleRoute}/bundles${params}`);
EDIT: catch test
it('should redirect if api fails', async () => {
const networkError = new Error('Some network error');
axios.mockRejectedValueOnce(networkError);
const goToUrl = jest.fn();
let error;
try {
await fetchBundlesFromApi('?params');
} catch (err) {
error = err;
}
expect(error).toEqual(networkError);
expect(goToUrl).toHaveBeenCalled();
});
in my component I import goToUrl like so:
import { goToUrl } from 'Helpers';
You can make use of Jests ability to pop implementations off once they've run i.e. mockImplementationOnce and friends.
import axios from 'axios';
jest.mock('axios');
// default implementation
axios.get.mockResolvedValue(mockedData);
describe('#fetchBundlesFromApi', () => {
it('returns data from API', async () => {
const fetchedBundles = await fetchBundlesFromApi('?params');
expect(fetchedBundles.data).toEqual(mockData);
});
it('redirects on failure', () => {
// override behaviour for this one call
axios.get.mockRejectedValueOnce();
// verify your failure test
});
});
Related
I have tried lots of answers to similar questions, but none of them helps. (the comments are what I have tried. attempts are separated by a blank line. I have stuck here for almost a week, trying to improve the coverage by testing the .then part of the Axios request. really cannot figure out which part goes wrong.
code here
__ mocks __/axios.js:
export default {
get: jest.fn(() => Promise.resolve({ data: {} })),
post: jest.fn(() => Promise.resolve())
}
getInfo method to be tested:
getInfo () {
axios.get('/')
.then((response) => {
this.form.sid = response.data.data.basic_info.username
this.form.name = response.data.data.basic_info.name
this.form.tel = response.data.data.basic_info.mobile_number
this.form.email = response.data.data.basic_info.email
return response.data
}).catch(function (error) {
console.log(error)
})
}
test code:
import { shallowMount } from '#vue/test-utils'
import InfoForm from '#/components/InfoForm'
//attempt 1
import axios from 'axios';
jest.mock('axios')
//attempt 2
// import axios from './__mocks__/axios'
// jest.mock('axios')
//attempt 3
// import axios from './__mocks__/axios'
// jest.mock("axios", () => ({
// post: jest.fn((_url, _body) => {
// url = _url
// body = _body
// return Promise.resolve()
// }),
// get: jest.fn(() => {
// return Promise.resolve()
// })
// }))
//attempt 4
// import axios from "axios"
//...
//describe part is skipped here
it('test method: getInfo', async () => {
const mockAxiosGet = jest.spyOn(axios, "get")
mockAxiosGet.mockResolvedValue(() =>
Promise.resolve({
data: {
basic_info: {
username: 'aName',
name: 'aNAME',
mobile_number: '12222222222',
email: 'amail#em.com'
}
}
})
)
const response = await wrapper.vm.getInfo()
expect(response).toBeDefined() // error(plz see error message below)
})
error message:
Ensure that a variable is not undefined.
InfoForm.vue test > test method: getInfo
-----
Error: expect(received).toBeDefined()
Received: undefined Jest
any help is highly appreciated!
getInfo is a common pitfall with promises. Promises shouldn't be encapsulated and should be returned from a function that contains them in order for them to be chained later. Even if this isn't currently needed, this may be needed later for a function to be composed or tested. The only reason to not do this is that a callback may need a specific signature that doesn't allow to return promise object.
It should be:
getInfo () {
return axios.get('/')
...
I want to mock the function forgotPassword inside the module authenticationPlugin/App, So i am doing this
jest.mock("authenticationPlugin/App", () => ({
forgotPassword (email: string) {
const msg='success'
email='a'
return msg
}
}))
Now i want to clear the mock of authenticationPlugin/App and have a different implementation for the forgotPassword method
So i did this
jest.clearAllMocks();
jest.mock("authenticationPlugin/App", () => ({
forgotPassword (email: string) {
throw new Error(<any>{'err':{'message':'Network Error'}})
}
}))
Now i expect the forgotPassword method to have a different implementation after clearing the mocks in for the module authenticationPlugin/App but it doesn't change...
If you want to have a different implementation for the mock in each test, you can use jest.fn instead.
Expanding on your code, it could look like this:
it('returns success', () => {
authApp.forgotPassword = jest.fn((email: string) => {
const msg='success'
email='a'
return msg
});
// Your test code here.
});
test('returns error', () => {
authApp.forgotPassword = jest.fn((email: string) => {
throw new Error(<any>{'err':{'message':'Network Error'}})
});
// Your test code here.
});
I want to test a route that makes external api calls.
I would like to stub the functionThatShouldBeStubbed so I can skip the external api call and focus on testing the route instead.
I am using Sinon and rewire, because if I understood correctly I cannot stub a function that was exported the way it currently is.
However, it seems like even though rewire replaced the function, my test is still making external api call. It seems like sinon is not aware that the function was rewired. How can I make this situation work?
//--------------------------
//../target.js
const functionThatShouldBeStubbed = async () => {
const results = await external_API_call();
return results;
}
module.exports = {
functionThatShouldBeStubbed,
/*more other functions*/
}
//--------------------------
//../index.js
app.use(require('endpoint.js'));
//--------------------------
//endpoint.js
const { functionThatShouldBeStubbed } = require("target.js");
router.post('endpoint', async(req, res) => {
//do lots of stuff
const results = await functionThatShouldBeStubbed();
if(results.error) { return res.status(207).send({ /*stuff */})}
//...more stuff
})
//--------------------------
//test.js
const server = require("../index.js");
const rewire = require('rewire')
const restoreTarget = rewire('../target.js');
describe("Should return appropriate error code to requester", function () {
it("Should return 207 in this case", function (done) {
const targetStub = sinon.stub().resolves({msg: 'fake results', statusCode: 207})
const targetRewired = restoreTarget.__set__("functionThatShouldBeStubbed", targetStub);
chai.request(server)
.post("/endpoint")
.send('stuff over')
.catch((error) => {
console.log("Error: ", error)
done();
})
.then((res) => {
expect(targetStub.callCount).to.equal(1);
res.should.have.status(207);
restoreTarget();
targetStub.restore();
done();
})
})
})
Many thanks!
Edit: updated code for more detail
Edit2: updated code again to show import method
You shouldn't need rewire at all here based on how your module is being exported. The following should work
//test.js
const target = require ("../target");
const server = require("../index");
describe("Should return appropriate error code to requester", () => {
it("Should return 207 in this case", done => {
const targetStub = sinon
.stub(target, "functionThatShouldBeStubbed")
.resolves({msg: 'fake results', statusCode: 207})
chai.request(server)
.post("/endpoint")
.send('stuff over')
.then(res => {
expect(targetStub.callCount).to.equal(1);
res.should.have.status(207);
targetStub.restore();
done();
})
})
})
I am trying to test a function which is an api call / promise so I can check state inside then using jest but cant seem to figure out what to do. I have tried mocking the file and the function to return a promise but getting an error TypeError: (0 , _dataAccess.fetchBundlesFromApi) is not a function I've tried following the docs on jests website and also the many different answers from stack overflow but none seem to work. Here is the code I want to test. I want to be able to call that and then say if okay check state or if error do something else. below is the code i am trying to do and the mocking that I have tried.
getLatestPrices = params => {
const { updateBundles } = this.props;
fetchBundlesFromApi(params)
.then(({ data: { bundles } }) => {
updateBundles(bundles);
this.setState({ showUpdatingPrices: false });
window.TemplateCalculator.reload();
})
.catch(() => goToUrl(bundlesUrl));
};`
fetchBundlesFromApi is import { fetchBundlesFromApi } from '../../../../dataAccess'; which is an axios call:
const fetchBundlesFromApi = params => axios(`${bundleRoute}/bundles${params}`);
export { fetchBundlesFromApi };
This is the mocking I have tried.
jest.mock('../../../../dataAccess', () => ({
fetchBundlesFromApi: new Promise(resolve => resolve({ data: mockBundles })),
}));
I have also tried these websites:
https://binarapps.com/blog/test-ajax-calls-in-react-component-lifecycle.
Jest/Enzyme Error: "Method 'setState' is only meant to run on a single node. 3 found instead."
https://jestjs.io/docs/en/asynchronous
I worked out I had to import my api call function like so:
import { fetchBundlesFromApi } from '../../../../dataAccess';
As that function was using axios I had to mock that. I did that like so:
jest.mock('axios', () => jest.fn(() => Promise.resolve({ data: mockBundles })));
The in my test I made it async and I could await that function response.
const fetchedBundles = await fetchBundlesFromApi(
'params',
);
How is the proper way to unit test the following redux async action?
const client = contentful.createClient(clientConfig);
export const fetchNavigation = () => {
return dispatch => {
return client.getEntries({content_type: 'navigation'})
.then((entries) => {
console.log('All entries for content_type = navigation')
dispatch(receiveNavigation(entries))
})
.catch(error => {
console.log('Something went wrong');
dispatch(fetchNavigationFailure(error));
});
}
}
I don't know how to customise the web request response body performed by client.getEntries. I think that replacing the getEntries function with my own one would do the trick. However, I don't know where to start to do that.
Here is the unit test I wrote:
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
describe('fetchNavigation', () => {
it('creates RECEIVE_NAVIGATION when fetching navigation is done', () => {
// Here I should prepare the client.getEntries() returned promise
const expectedBodyResponse = { includes: ['do something', 'yay!'] }
const expectedActions = [
{ type: actions.RECEIVE_NAVIGATION, navigation: expectedBodyResponse }
]
const store = mockStore({ todos: [] })
return store.dispatch(actions.fetchNavigation())
.then(() => {
expect(store.getActions()).toEqual(expectedActions)
})
})
})
IMO mocking getEntries (and probably createClient) seems to be the right way to do. :)
It depends how you load the contentful sdk. As I see you're using ES Modules and Jasmine, right?
To mock the getEntries function you have to mock the createClient as the client is not accessible from within your test.
I think this this answer might be what you're looking for.
I just wrote down an example.
import contentful from 'contentful';
export const fetchNavigation = () => {
return (dispatch) => {
return contentful.createClient({ accessToken: 'fooo', space: 'bar' })
.getEntries({ content_type: 'navigation' })
.then(() => {
dispatch('yeah');
})
.catch(error => console.error('Something went wrong', error));
};
};
import { fetchNavigation } from '../Action';
import * as contentful from 'contentful';
describe('Contentful mocking', () => {
it('should be possible to mock Contentful', (done) => {
const client = { getEntries: () => { return Promise.resolve(); } };
const spy = {
fn: (value) => {
expect(value).toBe('yeah');
done();
},
};
spyOn(contentful.default, 'createClient').and.returnValue(client);
fetchNavigation()(spy.fn);
});
});
I had to move the createClient call into the action itself, because otherwise I don't think it's possible to reach and mock it when it's hidden in the module scope. I then used the import * as contentful from 'contentful' to mock and overwrite the needed functionality and to have the flexibility to adjust everything to my needs.
The usage of the createClient feels a bit unfortunate for me. I'd probably restructure everything a bit and would pass the client as dependency of all the actions? This way the mocking would become way easier and when you also have several action modules, there is most probably no need to initialize the client several times?
I solved in this way.
First I moved the creation of the client to its own file with functions initClient() and getClient(). The module is called contentfulClient.
Then, I found out that it is possible to mock the function of an instantiated object in sinon:
import * as contentful from './services/contentfulClient';
const client = contentful.initClient(clientConfig);
const navigation = {
items: ['page1', 'page2']
};
// Returns a promise with navigation as content
sinon.stub(client, 'getEntries').resolves(navigation);
// Assert
return store.dispatch(actions.fetchNavigation())
.then( () => { expect(store.getActions()).toEqual(expectedActions)
})