Bare-bones

2024-9-7 Less than 1 minute

In a bare-bones example, you just import http-request-mock into your module entry(such as: src/index.js, components/abc.vue) and configure your mock datas there. Take a Vue project as an example:


Hit F12 to access Developer Tools and view the console logs.

<template>
  <div class="demo">
    <button @click="getResult">Get https://some.api.com/some-path</button>
    <div class="result"> {{ msg }} </div>
    <div class="tips">Hit F12 to access Developer Tools and view the console logs.</div>
  </div>
</template>

<script>
import HttpRequestMock from 'http-request-mock/http-request-mock.js';
import axios from 'axios';
export default {
  data() {
    return { msg: '' }
  },
  mounted() {
    const mocker = HttpRequestMock.setup()
    mocker.get('https://some.api.com/some-path', '<div>some result</div>');
  },
  methods: {
    getResult() {
      axios.get('https://some.api.com/some-path').then(res => {
        this.msg = res.data;
      }).catch(err => {
        this.msg = 'error: ' + err.message;
      })
    }
  }
}
</script>
<style scoped src="./demo.css">

It may be ok in a small project, however, for a large web application, it may have lots of APIs to be mocked. You may need frequently change the entry file when adding/deleting/updating a mock data. There will be a day that you'll get a mess as the project grows.

Last update: September 7, 2024 15:58