Describe API specification as a test
npm install api-first-specThis is a solution for that situation.
bash
npm install api-first-spec
`
How to define spec
Example is like this.` javascript
var spec = require("../lib/api-first-spec");var API = spec.define({
name: "Sign in",
description:
,
endpoint: "/auth/signin",
method: "POST",
request: {
contentType: spec.ContentType.URLENCODED,
params: {
email: "string",
password: "string",
remember_me: "boolean"
},
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 40
}
}
},
response: {
contentType: spec.ContentType.JSON,
data: {
code: "int",
message: "string",
result: {
id: "int",
name: "string",
imageUrl: "string",
lastLogin: "datetime"
}
},
rules: {
code: {
required: true
},
result: {
required: function(data) {
return data.code === 200;
}
},
"result.id": {
required: true
},
"result.name": {
required: true
},
}
}
});module.exports = API;
`Probably most of engineers can read it without special knowlegde.
Detailed reference is here
How to make test
You can make test with mochaExample is like this.
` javascript
var assert = require("chai").assert;
var SigninAPI = require("./Signin.spec.js");describe("signin", function() {
var host = spec.host("localhost:9000");
it("succeed with corrct email and password", function(done) {
return host.api(API).params({
"email": "test@test.com",
"password": "password"
}).success().then(data => {
assert.equal(data.code, 200);
assert.equal(data.result.id, 1);
assert.equal(data.result.name, "test");
});
});
it("with wrong email should be badRequest", () => {
return host.api(SigninAPI).params({
email: "unknown@test.com",
password: "password"
}).badRequest();
});
it("with wrong password should be badRequest", function(done) {
return host.api(API).params({
"email": "test@test.com",
"password": "PASSWORD"
}).badRequest();
});
});
`spec#host` method returns a HttpClient.