javascript - Mocking Axios calls using Moxios in order to test API calls -


i have following custom axios instance:

import axios 'axios'  export const base_url = 'http://jsonplaceholder.typicode.com'  export default axios.create({   baseurl: base_url }) 

with corresponding service:

import http './http'  export async function fetchuserposts(id) {   const reponse = await http.get(`/users/${id}/posts`)   return reponse.data } 

and test said service:

import moxios 'moxios' import sinon 'sinon' import http '@/api/http' import { fetchuserposts } '@/api/usersservice'  describe('users service', () => {   beforeeach(() => {     moxios.install(http)   })    aftereach(() => {     moxios.uninstall(http)   })    it('fetches posts of given user', (done) => {     const id = 1     const expectedposts = ['post1', 'post2']      moxios.stubrequest(`/users/${id}/posts`, {       status: 200,       response: expectedposts     })      const onfulfilled = sinon.spy()     fetchuserposts(1).then(onfulfilled)      moxios.wait(() => {       expect(onfulfilled.getcall(0).args[0].data).tobe(expectedposts)       done()     })   }) }) 

which when executed using karma + jasmine raises following error:

uncaught typeerror: cannot read property 'args' of null thrown 

what test when endpoint /users/{id}/posts hit mocked response sent back. while using custom axios instance http.

i've tried stubbing first example of documentation of moxios shows. don't think fits use case, check request formed correctly in service.

i've tried following code, works expected, test service (which following code does not do):

import axios 'axios' import moxios 'moxios' import sinon 'sinon'  describe('users service', () => {   beforeeach(() => {     moxios.install()   })    aftereach(() => {     moxios.uninstall()   })    it('fetches posts of given user', (done) => {     const id = 1     const expectedposts = ['post1', 'post2']      moxios.stubrequest(`/users/${id}/posts`, {       status: 200,       response: expectedposts     })      const onfulfilled = sinon.spy()     axios.get(`/users/${id}/posts`).then(onfulfilled)      moxios.wait(() => {       expect(onfulfilled.getcall(0).args[0].data).tobe(expectedposts)       done()     })   }) }) 

any ideas on how fix error?


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -