DEV Community

Alexandr K
Alexandr K

Posted on

3

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay