egg-node-cheat1 v1.0.0
egg-node
$ back
Mock library for testing Egg applications, plugins and custom Egg frameworks with ease. egg-mock inherits all APIs from node_modules/mm, offering more flexibility.
Install
Usage
$ npm i egg-node --save-dev
Create testcase Launch a mock server with mm.app
app/controller/list
'use strict';
const Controller = require('egg').Controller;
const createRule = {
name: 'string',
content: 'string',
url: 'string'
}
const createId = {
id:'id'
}
class ListController extends Controller {
async index() {
const { ctx } = this;
const { page = 1, pageSize = 5, search = '' } = ctx.query;
try {
let res = await ctx.service.list.getlist(page, pageSize, search);
ctx.body = {
code: 0,
mes: 'success',
...res
};
} catch (error) {
ctx.body = {
code: 1,
mes: 'fail'
}
}
}
async create() {
const { ctx } = this;
let { name, content, url } = ctx.request.body;
ctx.validate(createRule, ctx.request.body);
let res = await ctx.service.list.add(ctx.request.body);
if (res.affectedRows == 1) {
ctx.body = {
code: 0,
mes: 'Added successfully'
}
} else {
ctx.body = {
code: 0,
mes: 'Add failed'
}
}
}
Retrieve Agent instance through app.agent after mm.app started.
Using mm.cluster launch cluster server, you can use the same API as mm.app;
Test Application baseDir is optional that is process.cwd() by default.
async update() {
const { ctx } = this;
// const {name,content,url} = ctx.request.body;
const { id } = ctx.params;
ctx.validate({...createRule,...createId},{...ctx.request.body,...ctx.params});
let res = await ctx.service.list.edit({...ctx.request.body,...ctx.params});
if (res.affectedRows == 1) {
ctx.body = {
code: 0,
mes: 'Edit succeeded'
}
} else {
ctx.body = {
code: 0,
mes: 'Edit failed'
}
}
}
Test Framework
framework is optional, it's node_modules/egg by default.
async destroy() {
const {ctx} = this;
let {id} = ctx.params;
ctx.validate(createId,ctx.params);
let res = await ctx.service.list.del(ctx.params);
if (res.affectedRows == 1) {
ctx.body = {
code: 0,
mes: 'Delete succeeded'
}
} else {
ctx.body = {
code: 0,
mes: 'Deletion failed'
}
}
}
}
module.exports = ListController;
Test Plugin
If eggPlugin.name is defined in package.json, it's a plugin that will be loaded to plugin list automatically.
You can also test the plugin in different framework, e.g. test aliyun-egg and framework-b in one plugin.
If it's detected as an plugin, but you don't want it to be, you can use plugin = false
.
app/controller/user
'use strict';
const Controller = require('egg').Controller;
const svgCaptcha = require('svg-captcha');
const axios = require('axios');
const fs = require('mz/fs');
const createRule = {
name: 'string',
pwd: 'password',
phone: 'phone',
email: 'email'
}
const createLogin = {
name: 'string',
pwd: 'password',
captcha: 'string'
}
API
mm.app(options) Create a mock application.
mm.cluster(options) Create a mock cluster server, but you can't use API in application, you should test using supertest.
class UserController extends Controller {
async registry() {
const { ctx } = this;
const { name, pwd, phone, email, sex } = ctx.request.body;
ctx.validate(createRule, ctx.request.body);
let user = await ctx.service.user.getuser(name);
if (user) {
ctx.body = {
code: 3,
mes: 'The mobile phone number has been registered. Please log in directly'
}
return;
}
let res = await ctx.service.user.registry({ ...ctx.request.body, pwd: ctx.helper.cryptopwd(pwd), avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png' });
console.log(res)
if (res.affectedRows == 1) {
ctx.body = {
code: 0,
mes: 'login was successful'
}
} else {
ctx.body = {
code: 1,
mes: 'login has failed'
}
}
}
async getcaptcha() {
const { ctx } = this;
let captcha = svgCaptcha.create({
size: 4,
noise: 3,
color: true,
width: 100,
height: 40,
fontSize: 50
});
ctx.session.captcha = captcha.text;
console.log(captcha.text)
ctx.response.type = 'svg';
ctx.body = captcha.data;
}
async login() {
const { ctx } = this;
const { name, pwd, captcha } = ctx.request.body;
ctx.validate(createLogin, ctx.request.body);
if (ctx.session.captcha.toUpperCase() !== captcha.toUpperCase()) {
ctx.body = {
code: 2,
mes: 'Inconsistent verification code'
}
return;
}
let user = await ctx.service.user.getuser(name);
if (!user) {
ctx.body = {
code: 3,
mes: 'This user has not been registered, please register first'
}
return;
}
let res = await ctx.service.user.login({ name, pwd: ctx.helper.cryptopwd(pwd) });
if (res.length > 0) {
ctx.body = {
code: 0,
name: res[0].name,
avatar: res[0].avatar,
token: ctx.helper.gettoken({ name: res[0].name, id: res[0].id }),
mes: 'Login succeeded'
}
} else {
ctx.body = {
code: 1,
mes: 'Login failed'
}
}
}
async getuser() {
const { ctx } = this;
let { code } = ctx.query;
if (!code) {
ctx.body = {
code: 2,
mes: 'Missing parameter'
}
return;
}
let config = ctx.app.config.gitee;
let res = await axios.post('https://gitee.com/oauth/token', {
grant_type: 'authorization_code',
code,
client_id: config.client_id,
redirect_uri: config.redirect_uri,
client_secret: config.client_secret
});
let access_token = res.data.access_token;
let user = await axios.get('https://gitee.com/api/v5/user', {
params: {
access_token
}
});
ctx.body = {
code: 0,
token: ctx.helper.gettoken({ name: user.data.name, id: user.data.id }),
data: user.data
}
}
You can disable coverage, because it's slow.
async upload() {
const { ctx } = this;
const file = ctx.request.files[0];//Get file information
const name = 'files/' + ctx.helper.createName(file.filename);
let result;
try {
result = await ctx.oss.put(name, file.filepath);
} finally {
await fs.unlink(file.filepath);
}
mm.env(env) Mock env when starting
ctx.body = {
code:0,
url: result.url,
requestBody: ctx.request.body,
};
}
}
module.exports = UserController;
app/extend/helper
const { createHmac } = require('crypto');
const jwt = require('jsonwebtoken');
const path = require('path');
const md5 = require('md5');
module.exports = {
cryptopwd(pwd) {
const secret = '1903a';
return createHmac('sha256', secret)
.update(pwd)
.digest('hex');
},
gettoken(data) {
return jwt.sign(data, this.app.config.keys, { expiresIn: '10h' });
},
createName(name) {
let extname = path.extname(name);
let basename = path.basename(name, extname);
let url = JSON.stringify({
basename,
time: new Date().getTime()
})
return md5(url) + extname;
}
};
3 years ago