DEV Community

Alexandr K
Alexandr K

Posted on

Testing REST API in VueJS

I've just started to work with VueJS on building prototypes of dashboard for my analytics works in the current company. VueJS is so simple that it became my favorite tool for building js apps. In EmberJS everyone is using mirage library to stub api calls and respond with the required bodies. In VueJS I've decided to archive the same behavior by using vue-resource-mock

Lets push some examples there for easy understanding how to use this awesome 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)
}
...
Enter fullscreen mode Exit fullscreen mode
// 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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

And finally if you have component where you are using http resource to get the data it should be the same as before, no changes required, just call http request and you will get mocked data.

...

      this.$http
        .get(`${process.env.API_HOST}/example`)
        .then(response => {
          let { collection1 } = response.body
          this.$store.commit('setCollection1', collection)
        })
...
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)