title: Unit testing HTTP request with Vue, Axios, and Mocha
body: <p>I'm really struggling trying to test a request in VueJS using Mocha/Chai-Sinon, with Axios as the request library and having tried a mixture of Moxios and <code>axios-mock-adaptor</code>. The below examples are with the latter.</p>
  
  <p>What I'm trying to do is make a request when the component is created, which is simple enough.</p>
  
  <p>But the tests either complain about the <code>results</code> variable being undefined or an <code>async timout</code>.</p>
  
  <p>Am I doing it right by assigning the variable of the <code>getData() function? Or should I</code>return` the values? Any help would be appreciated.</p>
  
  <p><strong>Component</strong></p>
  
  <pre><code>  // 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
            })
        }
      }
    }
  </code></pre>
  
  <p><strong>Test</strong></p>
  
  <pre><code>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', () =&gt; {
    it('should update the results variable with results', (done) =&gt; {
      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(() =&gt; {
        expect(VM.results).to.be.null
        done()
      }, 1000)
    })
  })
  </code></pre>