Gathering detailed insights and metrics for @zhennann/egg-mock
Gathering detailed insights and metrics for @zhennann/egg-mock
Gathering detailed insights and metrics for @zhennann/egg-mock
Gathering detailed insights and metrics for @zhennann/egg-mock
npm install @zhennann/egg-mock
Typescript
Module System
Min. Node Version
Node Version
NPM Version
51.9
Supply Chain
93
Quality
67.8
Maintenance
100
Vulnerability
97.6
License
TypeScript (99.67%)
JavaScript (0.33%)
Love this project? Help keep it running — sponsor us today! 🚀
Total Downloads
20,840
Last Day
2
Last Week
5
Last Month
32
Last Year
317
MIT License
145 Stars
303 Commits
31 Forks
26 Watchers
12 Branches
40 Contributors
Updated on Feb 08, 2025
Latest Version
4.2.4
Package Id
@zhennann/egg-mock@4.2.4
Unpacked Size
71.32 kB
Size
19.83 kB
File Count
25
NPM Version
9.5.0
Node Version
18.14.2
Published on
Nov 12, 2023
Cumulative downloads
Total Downloads
Last Day
100%
2
Compared to previous day
Last Week
-58.3%
5
Compared to previous week
Last Month
77.8%
32
Compared to previous month
Last Year
-92.9%
317
Compared to previous year
21
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.
1$ npm i egg-mock --save-dev
Launch a mock server with mm.app
1// test/index.test.js 2const path = require('path'); 3const mm = require('egg-mock'); 4 5describe('some test', () => { 6 let app; 7 before(() => { 8 app = mm.app({ 9 baseDir: 'apps/foo' 10 }); 11 return app.ready(); 12 }) 13 after(() => app.close()); 14 15 it('should request /', () => { 16 return app.httpRequest() 17 .get('/') 18 .expect(200); 19 }); 20});
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
;
baseDir
is optional that is process.cwd()
by default.
1before(() => { 2 app = mm.app(); 3 return app.ready(); 4});
framework is optional, it's node_modules/egg
by default.
1before(() => { 2 app = mm.app({ 3 baseDir: 'apps/demo', 4 framework: true, 5 }); 6 return app.ready(); 7});
If eggPlugin.name
is defined in package.json
, it's a plugin that will be loaded to plugin list automatically.
1before(() => { 2 app = mm.app({ 3 baseDir: 'apps/demo', 4 }); 5 return app.ready(); 6});
You can also test the plugin in different framework, e.g. test aliyun-egg and framework-b in one plugin.
1describe('aliyun-egg', () => { 2 let app; 3 before(() => { 4 app = mm.app({ 5 baseDir: 'apps/demo', 6 framework: path.join(__dirname, 'node_modules/aliyun-egg'), 7 }); 8 return app.ready(); 9 }); 10}); 11 12describe('framework-b', () => { 13 let app; 14 before(() => { 15 app = mm.app({ 16 baseDir: 'apps/demo', 17 framework: path.join(__dirname, 'node_modules/framework-b'), 18 }); 19 return app.ready(); 20 }); 21});
If it's detected as an plugin, but you don't want it to be, you can use plugin = false
.
1before(() => { 2 app = mm.app({ 3 baseDir: 'apps/demo', 4 plugin: false, 5 }); 6 return app.ready(); 7});
Create a mock application.
Create a mock cluster server, but you can't use API in application, you should test using supertest
.
1const mm = require('egg-mock'); 2describe('test/app.js', () => { 3 let app, config; 4 before(() => { 5 app = mm.cluster(); 6 return app.ready(); 7 }); 8 after(() => app.close()); 9 10 it('some test', () => { 11 return app.httpRequest() 12 .get('/config') 13 .expect(200) 14 }); 15});
You can disable coverage, because it's slow.
1mm.cluster({ 2 coverage: false, 3});
Mock env when starting
1// production environment 2mm.env('prod'); 3mm.app({ 4 cache: false, 5});
Environment list https://github.com/eggjs/egg-core/blob/master/lib/loader/egg_loader.js#L82
Mock level that print to stdout/stderr
1// DON'T log to terminal 2mm.consoleLevel('NONE');
level list: DEBUG
, INFO
, WARN
, ERROR
, NONE
mock home directory
restore all mock data, e.g. afterEach(mm.restore)
Options for mm.app
and mm.cluster
The directory of application, default is process.cwd()
.
1mm.app({ 2 baseDir: path.join(__dirname, 'fixtures/apps/demo'), 3})
You can use a string based on $CWD/test/fixtures
for short
1mm.app({ 2 baseDir: 'apps/demo', 3})
The directory of framework
1mm.app({ 2 baseDir: 'apps/demo', 3 framework: path.join(__dirname, 'fixtures/egg'), 4})
It can be true when test an framework
The directory of plugin, it's detected automatically.
1mm.app({ 2 baseDir: 'apps/demo', 3})
Define a list of plugins
Determine whether enable cache. it's cached by baseDir.
Clean all logs directory, default is true.
If you are using ava
, disable it.
Assert some string value in the logger instance.
It is recommended to pair app.mockLog()
with app.expectLog()
or app.notExpectLog()
.
Using app.expectLog()
or app.notExpectLog()
alone requires dependency on the write speed of the log. When the server disk is high IO, unstable results will occur.
1it('should work', async () => { 2 app.mockLog(); 3 await app.httpRequest() 4 .get('/') 5 .expect('hello world') 6 .expect(200); 7 8 app.expectLog('foo in logger'); 9 app.expectLog('foo in coreLogger', 'coreLogger'); 10 app.expectLog('foo in myCustomLogger', 'myCustomLogger'); 11 12 app.notExpectLog('bar in logger'); 13 app.notExpectLog('bar in coreLogger', 'coreLogger'); 14 app.notExpectLog('bar in myCustomLogger', 'myCustomLogger'); 15});
Request current app http server.
1it('should work', () => { 2 return app.httpRequest() 3 .get('/') 4 .expect('hello world') 5 .expect(200); 6});
See supertest to get more APIs.
Assert current response not contains the specified header
1it('should work', () => { 2 return app.httpRequest() 3 .get('/') 4 .unexpectHeader('set-cookie') 5 .expect(200); 6});
Assert current response contains the specified header
1it('should work', () => { 2 return app.httpRequest() 3 .get('/') 4 .expectHeader('set-cookie') 5 .expect(200); 6});
1const ctx = app.mockContext({ 2 user: { 3 name: 'Jason' 4 } 5}); 6console.log(ctx.user.name); // Jason
1app.mockCookies({ 2 foo: 'bar' 3}); 4const ctx = app.mockContext(); 5console.log(ctx.getCookie('foo'));
Mock request header
1app.mockSession({ 2 foo: 'bar' 3}); 4const ctx = app.mockContext(); 5console.log(ctx.session.foo);
1it('should mock user name', function* () { 2 app.mockService('user', 'getName', function* (ctx, methodName, args) { 3 return 'popomore'; 4 }); 5 const ctx = app.mockContext(); 6 yield ctx.service.user.getName(); 7});
You can mock an error for service
1app.mockServiceError('user', 'home', new Error('mock error'));
1app.mockCsrf(); 2 3return app.httpRequest() 4 .post('/login') 5 .expect(302);
Mock httpclient request, e.g.: ctx.curl
1app.get('/', function*() { 2 const ret = yield this.curl('https://eggjs.org'); 3 this.body = ret.data.toString(); 4}); 5 6app.mockHttpclient('https://eggjs.org', { 7 // can be buffer / string / json / function 8 // will auto convert to buffer 9 // follow options.dataType to convert 10 data: 'mock egg', 11}); 12// app.mockHttpclient('https://eggjs.org', 'get', mockResponse); // mock get 13// app.mockHttpclient('https://eggjs.org', [ 'get' , 'head' ], mockResponse); // mock get and head 14// app.mockHttpclient('https://eggjs.org', '*', mockResponse); // mock all methods 15// app.mockHttpclient('https://eggjs.org', mockResponse); // mock all methods by default 16// app.mockHttpclient('https://eggjs.org', 'get', function(url, opt) { return 'xxx' }); // support fn 17 18return app.httpRequest() 19 .post('/') 20 .expect('mock egg');
You can also use Regular Expression for matching url.
1app.mockHttpclient(/\/users\/[a-z]$/i, {
2 data: {
3 name: 'egg',
4 },
5});
You can alse mock agent.httpclient
1app.agent.mockHttpclient('https://eggjs.org', {
2 data: {
3 name: 'egg',
4 },
5});
We also provide a bootstrap file for applications' unit test to reduce duplicated code:
1const { app, mock, assert } = require('egg-mock/bootstrap'); 2 3describe('test app', () => { 4 it('should request success', () => { 5 // mock data will be restored each case 6 mock.data(app, 'method', { foo: 'bar' }); 7 return app.httpRequest() 8 .get('/foo') 9 .expect(res => { 10 assert(!res.headers.foo); 11 }) 12 .expect(/bar/); 13 }); 14});
Please open an issue here.
No vulnerabilities found.
No security vulnerabilities found.