Testing REST API in VueJS

#javascript#vue#vuejs#js

I recently started working with VueJS to build dashboard prototypes for analytics at my company. The simplicity of VueJS has quickly made it my favorite tool for JavaScript application development. While EmberJS developers commonly use the Mirage library to stub API calls and generate response bodies, for VueJS I've found vue-resource-mock to be an excellent alternative.

Let me share some examples to demonstrate how to use this powerful library:

// main.js
...
import VueResource from 'vue-resource'
import VueResourceMock from 'vue-resource-mock'
import MockData from './mock/data.js'

Vue.use(VueResource)

if (process.env.NODE_ENV === 'development') {
  Vue.use(VueResourceMock, MockData)
}
...
// mock/data.js

const id = () => Math.floor(Math.random() * 100)

export default {

  ['GET */example'] (pathMatch, query, request) {
    let body = {
      collection1: [
        { id: id(), name: 'name1' },
        { id: id(), name: 'name2' },
      ]
    }

    return {
      body: body,
      status: 200
    }
  }
}

The best part is that your component code remains unchanged. Simply make HTTP requests as usual, and you'll receive the mocked data during development:

...

      this.$http
        .get(`${process.env.API_HOST}/example`)
        .then(response => {
          let { collection1 } = response.body
          this.$store.commit('setCollection1', collection1)
        })
...
← Back to all posts

© Copyright 2023 Bitscorp