Reputation: 19294
I used to use axios-mock-adapter with great success, but the last few times i've tried to use it, my routes never seem to match and it is still trying to execute a real endpoint.
Why is this unit test still making a call to example.com and returning a 404? I would have expected it to return a 500.
test/libs/orgService/index.spec.js
const uuid = require('uuidv4')
const axios = require('axios')
const MockAdapter = require('axios-mock-adapter')
const mock = new MockAdapter(axios)
const { getOrgById } = require('../../../src/libs/orgService/index')
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
const expect = chai.expect
const orgServiceHost = 'https://example.com'
describe.only('#getOrgById failure', () => {
const id = uuid()
before(() => {
console.log('`${orgServiceHost}/organizations/${id}` = ', `${orgServiceHost}/organizations/${id}`)
mock.onGet(`${orgServiceHost}/organizations/${id}`).reply(500) <-- SHOULD BE RETURNING 500!!
})
after(() => {
mock.reset()
})
it('should fail to fetch an organization', () => {
return expect(getOrgById(orgServiceHost, id, tkn)).to.eventually.be.rejected
})
})
src/libs/orgService/index.js
const axios = require('axios')
function getOrgById (orgServiceHost, id, token) {
log.debug('orgServiceHost = ', orgServiceHost)
log.debug('id = ', id)
log.debug('token = ', token)
return new Promise((resolve, reject) => {
if (id === undefined) {
return resolve()
}
console.log('`${orgServiceHost}/organizations/${id}` = ', `${orgServiceHost}/organizations/${id}`)
axios({
url: `${orgServiceHost}/organizations/${id}`,
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json',
}
})
.then(res => {
return resolve(res.data)
})
.catch(err => {
log.error('getOrgById err = ', err)
return reject(err)
})
})
}
module.exports = { getOrgById }
Upvotes: 2
Views: 4273
Reputation: 902
Issue is that you return a Promise
from the service. Try something like:
it('should fail to fetch an organization', (done) => {
getOrgById(orgServiceHost, id, tkn)
.then(() => {
assert.fail("custom error message"); // or any other failure here
done();
}).catch((exception) => {
expect(true).toBeTruthy(); // or any other way to pass the test
done();
});
});
Upvotes: 0
Reputation: 19
(Note: I don't have enough credit to comment so posting the below as answer.)
I'm not sure if this will work but please try creating an axios instance
before(() => {
instance = AxiosApi.getAxiosInstance();
mock = new MockAdapter(instance);
mock.onGet(`${orgServiceHost}/organizations/${id}`).reply(500);
})
Upvotes: 1