egg-pload1 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/middleware/error_handler
module.exports = () => {
return async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
ctx.app.emit('error', err, ctx);
const status = err.status || 500;
const error = status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
ctx.body = { error };
if (status === 422) {
ctx.body.detail = err.errors;
}
ctx.status = status;
}
};
};
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.
$ app/middleware/jwt
const whiteList = ['/login', '/registry', '/getcaptcha','/getuser'];
const jwt = require('jsonwebtoken');
module.exports = () => {
return async (ctx, next) => {
if (whiteList.includes(ctx.path) || (ctx.method == 'GET' && ctx.path == '/list')) {
await next();
} else {
let token = ctx.request.headers.token;
if (!token) {
ctx.body = {
code: 4,
mes: 'No access'
}
ctx.status = 401;
return;
}
try {
jwt.verify(token, ctx.app.config.keys);
await next();
} catch (error) {
ctx.body = {
code: 5,
mes: 'Verification failed',
error
}
}
}
}
}
Test Framework
framework is optional, it's node_modules/egg by default.
$ app/service/list
'use strict';
const Service = require('egg').Service;
class ListService extends Service {
async add(obj) {
return await this.app.mysql.insert('list', obj);
}
async getlist(page,pageSize,search){
let startIndex = (page-1) * pageSize;
let total = await this.app.mysql.query(`select count(*) from list where name like '%${search}%'`);
let res =await this.app.mysql.query(`select * from list where name like '%${search}%' limit ${startIndex},${pageSize}`);
return {
total:total[0]['count(*)'],
data:res
}
}
async edit(obj){
return await this.app.mysql.update('list',obj);
}
async del(obj){
return await this.app.mysql.delete('list',obj);
}
}
module.exports = ListService;
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/service/user
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async getuser(name) {
return await this.app.mysql.get('ykuser', { name });
}
async registry(obj) {
return await this.app.mysql.insert('ykuser', obj);
}
async login(obj) {
return await this.app.mysql.select('ykuser', {
where: obj
});
}
}
module.exports = UserService;
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.
$ app/router
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller, validator } = app;
validator.addRule('phone', (rule, value) => {
if (!/^1[3456789]\d{9}$/.test(value)) {
return 'Mobile phone number verification failed'
}
})
router.get('/', controller.home.index);
router.post('/registry', controller.user.registry);
router.post('/login',controller.user.login);
router.get('/getcaptcha',controller.user.getcaptcha);
router.get('/getuser',controller.user.getuser);
router.post('/upload',controller.user.upload);
router.resources('list','/list',controller.list);
};
You can disable coverage, because it's slow.
$ app/config/config.default[userConfig]
// myAppName: 'egg',
security: {
csrf: false
},
gitee: {
client_id: '509e6a7b04da2018bb277b628984d6fc8cdc6b7759323a64ace470228c3a43d1',
client_secret: '985fdbc4ec574a7e75d12d92d505dcb0acf8eb70af5f0362d1a27215c4234fd0',
redirect_uri: 'http://localhost:3000/login'
},
oss: {
client: {
accessKeyId: 'LTAI5tKPfbNxu4q9FYSeVF4L',
accessKeySecret: '4Ei8JAc1UJKASJdNOC1iRk5cGGJ0SA',
bucket: 'webking',
endpoint: 'oss-cn-beijing.aliyuncs.com',
timeout: '60s',
},
},
mysql: {
client: {
host: 'localhost',
port: '3306',
user: 'root',
password: 'root',
database: '1903a',
},
app: true,
agent: false,
},
multipart: {
mode: 'file',
fileExtensions: ['.pdf']
}
mm.env(env) Mock env when starting
$ app/config/plugin[defult]
mysql: {
enable: true,
package: 'egg-mysql',
},
validate: {
enable: true,
package: 'egg-validate'
},
oss: {
enable: true,
package: 'egg-oss'
}
package
$ package
"egg-mysql": "^3.0.0",
"egg-oss": "^2.0.0",
"egg-scripts": "^2.11.0",
"egg-validate": "^2.0.2",
"jsonwebtoken": "^8.5.1",
"md5": "^2.3.0",
"svg-captcha": "^1.4.0"
3 years ago