This is the 9th day of my participation in the More text Challenge. For details, see more text Challenge

The [efficiency tools] interface debugging tools -Insomnia(1), Postman/Postwoman (2)-, – This article introduces the data interface simulation tool Mock Service Worker

Only when the reference, according to the need to eat, deficiencies, welcome each big man not hesitate to give advice, complement perfect, welcome to share


  • He that would do a good job must sharpen his tools. Practice promotes the development of science and technology
  • In the process of separating the front end and the back end, it is inevitable that the development process of the front end is earlier than that of the back end. In order to not be limited by the server interface, it is necessary to simulate the situation of the data interface
  • This article shares what happens at the front end of a projectmock api Data interface simulation tool, to help you develop and improve efficiency

Mock Service Worker

1. Introduction

Billed as the next generation API mock

API mocking of the next generation Mock by intercepting requests on the network level. Seamlessly reuse the same mock definition for testing, development, and debugging.

Why use it?

Mock Service Workers take advantage of standardized Service Worker apis designed to intercept requests at the network level, making the simulation completely seamless. Not only does this guarantee the behavior of the same application with and without simulation, but there is no need to make any changes to the application code in order to simulate.

[官网] : mswjs.io

【 原 文 】 : HoppScotch.io

[Github source] : Github/MSWJS

North Wall? -,-? Find your own ladder

2. Try the knife hand to hand: how to use it

The following solution is to create a project in vue-CLI and introduce how to use it. React is the same. Other methods are left to you to explore

2.1 Creating project filesYou can test ignore in an existing project

mkdir test-msw
cd test-msw
# vue-cli create a project
vue create <project-name>
Copy the code
  • The installation relies on MSW-d
yarn add msw --dev
Copy the code
  • Create the data simulation services folder
mkdir src/mocks
Copy the code

Let’s start defining the concrete logic code

2.2 createsrc/mocks/handler.js

touch src/mocks/handlers.js
Copy the code

In this case, we need to select the API type, Mocking REST API is chosen here

First of all, from 2.3mswLibrary into

// src/mocks/handlers.js
import { msw } from 'msw'
Copy the code

2.4 Here is the concrete logic: the request processing shelf

/ / shelf
// src/mocks/handlers.js
import { rest } from 'msw'

export const handlers = [
  // Handles a POST /login request
  rest.post('/login'.null),

  // Handles a GET /user request
  rest.get('/user'.null),]Copy the code

2.5 Specific code: Login judgment request

// src/mocks/handlers.js
import { rest } from 'msw'

export const handlers = [
  rest.post('/login'.(req, res, ctx) = > {
    // Persist user's authentication in the session
    sessionStorage.setItem('is-authenticated'.'true')

    return res(
      // Respond with a 200 status code
      ctx.status(200)
    )
  }),

  rest.get('/user'.(req, res, ctx) = > {
    // Check if the user is authenticated in this session
    const isAuthenticated = sessionStorage.getItem('is-authenticated')

    if(! isAuthenticated) {// If not authenticated, respond with a 403 error
      return res(
        ctx.status(403),
        ctx.json({
          errorMessage: 'Not authorized',}}))// If authenticated, return a mocked user details
    return res(
      ctx.status(200),
      ctx.json({
        username: 'admin'}))}),]Copy the code

2.6 Selecting the Running Environment

According to the document steps, we need to select the MSW runtime environment, here select Browser

touch src/mocks/browser.js
Copy the code

2.7 Registration Service

The code is simple, just introduce our request processing logic and register the service.

// src/mocks/browser.js
import { setupWorker } from 'msw'
import { handlers } from './handlers'

// This configures a Service Worker with the given request handlers.
export constworker = setupWorker(... handlers)Copy the code

2.8 Introducing services into projectsmain.ts

if (process.env.NODE_ENV === 'development') {
  const { worker } = require('./mocks/browser')
  worker.start()
}
Copy the code

Start item will print the service success status [MSW] Mocking Enabled in the debug bar

2.9 Test effect

On the test page pages/test/test.vue, simply write two buttons to send the request

<template>
  <div class="mock-service-worker">
    <button @click="handleLogin">login</button>
    <button @click="handleGetUser">get user</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'test',
  setup () {
    const handleLogin = () = > {
      fetch('/login', {
        method: 'POST'
      }).then((v) = > {
        console.log('v', v)
      })
    }

    const handleGetUser = () = > {
      fetch('user')
        .then((v) = > {
          return v.json()
        })
        .then((v) = > {
          console.log('v.json', v)
        })
    }

    return {
      handleLogin,
      handleGetUser
    }
  }
})
</script>

Copy the code

2.10 Starting Service 8080 and viewing the effect

2.10.1 clickloginThe request is sent and the following is successful

2.10.2 clickget-userGet the user name,

2.10.3 At this time, the user has logged in, and the user request can be obtained successfully. Let’s clear the login information and request again to see whether it is intercepted

2.10.4 Delete the login information, and request again because the login is not triggered by our processing logic, output403 Forbidden

Now that we’ve covered the Mock Service Worker library, it’s time to take a deeper dive into our project-specific logic.


Of course, there are many more useful mock API tools out there, but here are just a few, just for reference,

These can be customized according to their own needs, can greatly improve the efficiency of the code word, do you get it?

Please share your personal tools in the comments =, =

Today’s announcement will be updated tomorrow:

After talking about the next generation of front and back interface debugging tools, we plan to update some other data interface mock apis tomorrow

Stay tuned for the next installment of the next generation Mock API, which is fairly straightforward and easy to use. hahah~