“The data returned by the interface is not correct!” I think this is one of the things that front-end engineers talk about a lot. As front-end engineers, interface with back-end engineers is our daily work, and every time we encounter interface problems, we get a headache. In that case, can we find a way to deal with this problem? The following JSON Schema is one of my attempts.

JSON Schema

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.

JSON Schema is a document used to annotate and validate the metadata of JSON documents. In plain English, JSON Schema allows us to standardize and verify the format of JSON to meet our expectations. For example, a certain field is defined as string through JSON Schema, but the returned JSON field is number. In this case, the verification fails.

Here is a simple example of JSON Schema:

Let’s briefly analyze the meaning of this Schema:

  • The title field describes what the Schema is for. It is not binding.
  • Properties field: Describes the fields contained in this Schema
  • The firstName, lastName, and Age fields are the fields to be included in the JSON we are describing
  • Type field: Used to describe the type of field, this is required
  • Required field: Describes which fields are required

In this case, the following JSON will not pass because the age in the Schema is defined as an INTEGER.

{
   "firstName": "z",
   "lastName": "q",
   "age": "61"
}

Check the interface

Since the original project involves company information, demo is used here, but the idea is the same.

jsonschema

JSON Schema itself can be quite complex to describe. The current version is Draft-07. If our interface is simple JSON, that’s fine, but if it’s complex, it’s a bit of work to write well. So I recommend that you use jsonschema to help you automate it. Then, we can modify it on this basis.

ajv

Since this is to verify that our interface meets our expectations, it must be verified. There are a lot of libraries to check, but I use ajV library. With the function it provides, help us check, save a lot of trouble.

In actual combat

Check here, the theme of the CNODE request interface is https://cnodejs.org/api/v1/topics?page=1&limit=1

The interface format is as follows:

{ "success": true, "data": [ { "id": "5ae140407b0e8dc508cca7cc", "author_id": "573ab7ba542374db1db0a436", "tab": "Share ", "content":" XXX ", "title": "NODE PARTY ", "last_reply_at"," NODE PARTY ", "last_reply_at" "2018-06-01T03:01:08.368z ", "good": false, "top": true, "reply_count": 228, "visit_count": 8080," create_AT ": "2018-04-26T02:58:08.067z ", "author": {" loginName ":" AOJIAOtage ", "AVatar_URL ": "https://avatars3.githubusercontent.com/u/8339316?v=4&s=120" } } ] }Copy the code

The JSON Schema generated by JsonSchema is as follows:

{
  "$id": "http://example.com/example.json",
  "type": "object",
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "properties": {
    "success": {
      "$id": "/properties/success",
      "type": "boolean",
      "title": "The Success Schema ",
      "default": false,
      "examples": [
        true
      ]
    },
    "data": {
      "$id": "/properties/data",
      "type": "array",
      "items": {
        "$id": "/properties/data/items",
        "type": "object",
        "properties": {
          "id": {
            "$id": "/properties/data/items/properties/id",
            "type": "string",
            "title": "The Id Schema ",
            "default": "",
            "examples": [
              "5ae140407b0e8dc508cca7cc"
            ]
          },
         ....
}
Copy the code

As you can see, the generated JSON Schema is very formal, and we can set it to remove all non-essential fields.

Send a request through AXIos to get the returned message

const axios = require('axios'); const API = require('.. /api/index'); /** * Get cnode topic */ const getTopic = function () {return new Promise((resolve, reject) => { axios.get(API.topic) .then((response) => { resolve(response); }) .catch((error) => { reject(error); }); }) } module.exports = getTopic;

Then the data is verified by JSON Schema

const Ajv = require('ajv'); const ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} const chalk = require('chalk'); // schema const topicSchema = require('./schemas/cnode.topic.json'); // json const getTopic = require('./json/cnode.topic.js'); // check Topic function checkTopic () { getTopic() .then((resp) => { const validate = ajv.compile(topicSchema); const valid = validate(resp.data); console.log('---------------------------------------'); Console. log(' request URL: ${resp.request.path} '); If (valid) {console.log(' chalk. Green: ${valid} ')); } else {console.log(' chalk. Red: ${validate.errors} '); } console.log('---------------------------------------'); }) .catch((err) => { console.log('---------------------------------------'); Console. log(' request failed: ${err} ')); console.log('---------------------------------------'); }) } checkTopic();

runnode index.jsTo return to

The last

This example is simple, but there is a lot more work to be done to validate all the (important) interfaces in a business context. Such as

  • Environmental test
  • Automatically generates configurableJSON Schema
  • Timing/manual triggered verification
  • Verification reporting and statistics

In fact, I think this part should also belong to a part of automated testing, which is still being explored and improved.

JSON Schema interface test source code

Finally, mutual encouragement! 💪

👆 Return to home page for more articles 👆