Reputation: 19284
I want to test this method that logs (either to console.error, or a logger you pass in) properly.
/**
* Logs access errors in a way that is easy to quickly decipher the endpoint that was hit and the error that was received
*
* This was inspired from axios recommendation on handling errors https://www.npmjs.com/package/axios#handling-errors
*
* @param {Object | String} err The error we want to log
* @param {Object} [logger=console] An optional logger which defaults to console
* @public
* @since 5.3.0
*/
function logAxiosErr(err, logger = console) {
if (err.response) {
const error = {
error: `${err.response.status} - "${err.response.data}" with ${err.config.method.toUpperCase()} ${err.config.url}`,
headers: err.config.headers,
payload: err.config.data
}
// The request was made and the server responded with a status code that falls out of the range of 2xx
logger.error(error)
} else if (err.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
logger.error(err.request)
} else if (err.message) {
// Something happened in setting up the request that triggered an Error
logger.error(err.message)
} else {
logger.error(err)
}
This test obviously doesn't test anything. How can I improve it to actually test that what was logged is what I'm expecting?
describe('#logAxiosError', () => {
it('should log a string error ', () => {
const err = 'SOME ERROR'
expect(utils.logAxiosErr(err))
})
})
Upvotes: 0
Views: 83
Reputation: 727
One way to test dependency is to create a spy object (if using jasmine) for logger and pass it to logAxiosErr and then verify expectations on the spy object. So in your test above
describe('#logAxiosError', () => {
it('should log a string error ', () => {
const err = 'SOME ERROR'
var logger = jasmine.createSpyObj('logger', ['error']);
utils.logAxiosErr(err, logger);
expect(logger.error).toHaveBeenCalledWith(err);
})
})
Upvotes: 3