I have following method in vue file in which api call is there as below
getZipcode(city){
ajax.get(`${CONSTANTS.STANDARDAPIURL}Geographic/ZipCode?cityName=${city}`, {}, (res) => {
this.zipCode = res.data.zipCode
})
}
and i have defined this ajax in ajax.js file
window.ajax = {
get(url, params, successCallback, errorCallback,coordinates) {
var that = this;
let latitude = coordinates == undefined ? "" : coordinates.latitude
let longitude = coordinates == undefined ? "" : coordinates.longitude
axios({
method: "get",
url: that.formatURL(url),
params: params,
responseType: "json",
headers: { 'X-USER-COORDINATES': `${latitude},${longitude}`}
})
.then(function(response) {
if (
response.data.Message != null &&
response.data.Message != "" &&
response.data.Message ==
"Authorization has been denied for this request."
) {
window.location.href = "/account/login";
} else {
successCallback(response);
}
})
.catch(function(error) {
that.catchException(error, errorCallback);
});
} }
I have written test case as
test("getZipcode method", () => {
window.ajax = {
get: jest.fn()
}
var wrapper = mount(EmployeeInfo)
wrapper.vm.getZipcode('city')
expect(window.ajax.get).toHaveBeenCalled()
})
The test has been passed but the ajax call lines were not covered in code coverage as u can see in the image method coverage
Is there any way to write the test case to cover the ajax api calls
Thanks
I resolved the above problem with following test case
test(`getZipcode method`, () => {
var res = { data: { zipCode: '72015' } }
const mockAjax = sinon.stub(window.ajax, 'get').callsArgWith(2, res)
wrapper.vm.getZipcode('city')
sinon.assert.calledWith(window.ajax.get, `${CONSTANTS.STANDARDAPIURL}Geographic/ZipCode?cityName=city`)
mockAjax.restore()
})
Also installed babel-plugin-istanbul package and now the method covers as expected method coverage
Thanks