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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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