I am really trying to test a request in VueJS using Mocha / Chai-Sinon, with Axios as the request library and trying a mixture of Moxios and axios-mock-adaptor . Below are examples with the latter.
I am trying to make a request when a component is created, which is quite simple.
But the tests either complain about the results variable, which is undefined, or async timout .
Am I doing this right by assigning the variable getData() function? Or should I getData() function? Or should I return` values? Any help would be appreciated.
Component
// Third-party imports import axios from 'axios' // Component imports import VideoCard from './components/VideoCard' export default { name: 'app', components: { VideoCard }, data () { return { API: '/static/data.json', results: null } }, created () { this.getData() }, methods: { getData: function () { // I've even tried return instead of assigning to a variable this.results = axios.get(this.API) .then(function (response) { console.log('then()') return response.data.data }) .catch(function (error) { console.log(error) return error }) } } }
Test
import Vue from 'vue' import App from 'src/App' import axios from 'axios' import MockAdapter from 'axios-mock-adapter' let mock = new MockAdapter(axios) describe('try and load some data from somewhere', () => { it('should update the results variable with results', (done) => { console.log('test top') mock.onGet('/static/data.json').reply(200, { data: { data: [ { id: 1, name: 'Mexican keyboard cat' }, { id: 2, name: 'Will it blend?' } ] } }) const VM = new Vue(App).$mount setTimeout(() => { expect(VM.results).to.be.null done() }, 1000) }) })
source share