Install Mocha, supertest and configure Mocha

npm i mocha supertest -D
Copy the code

Note the configuration of the –exit operator in package.json’s script.test to automatically close the script after it has finished running

{ 
  "scripts": {
    "test": "mocha --exit"}}Copy the code

Two. Actual combat test project interface

1. Write a simple server

//app.js
const Koa = require('koa2');
const app = new Koa();
app.use((ctx,next) = >{
    ctx.response.type = 'text/html';
    ctx.body = `${ctx.url}`;
});
module.exports = app;
Copy the code

2. Write test code

//app.test.js
const 
    request = require('supertest'),
    app = require('.. /app');
describe('#test koa app'.function(){
    let server = app.listen(9900);
    describe('#test server'.function(){
        it('#test GET /'.async function(){
           await request(server).get('/sky').expect(200.'/sky'); })})})Copy the code

3. Take a test

skymac@skymacdeMBP machajs % npm test

> [email protected] test /Users/skymac/Desktop/all-demo/machajs
> mocha
  #test koa app
    #test server(23361) node: [DEP0066] DeprecationWarning: OutgoingMessage. Prototype. _headers is deprecated ✓#test GET /


  1 passing (25ms)
Copy the code

9cka.cn/study/10