koa-generator 單元測(cè)試
npm i jest mocha supertest -S
package.js
"scripts": {
"test": "cross-env NODE_ENV=staging jest --runInBand --forceExit --colors"
},
根目錄創(chuàng)建test文件夾,文件夾創(chuàng)建.test.js文件
user.test.js
const app = require('../app');
const request = require('supertest')(app.listen());
const { expect } = require('chai')
describe('api test', () => {
it('#user test success', async () => {
await request
.post('/login')
.send({ username: 'test', password: '123456' })
.expect('Content-Type', /json/)
.expect(200)
.expect(res => {
expect(res.body.status).to.be.true
});
});
});
帶token請(qǐng)求:
tokenTest.js
const config = require('../config')
const { sign } = require('jsonwebtoken');
const token = sign({username: 'test', password: '123456' , id: "123456"}, config.secret, {expiresIn: config.expiresIn});
const authorization = {authorization: `Bearer ${token}`}
module.exports = authorization
api.test.js
const app = require('../app');
const request = require('supertest')(app.listen());
const { expect } = require('chai')
const authorization = require('./tokenTest');
describe('test api', () => {
it('#test ccreate api', async () => {
await request
.post('/api')
.set(authorization)
.send({ test: 'test' })
.expect(200)
.expect(res => {
expect(res.body.status).to.be.true
});
})
})
npm run test