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.
The directory of plugin, it’s detected automatically.
mm.app({
baseDir: 'apps/demo',
})
plugins {Object}
Define a list of plugins
cache {Boolean}
Determine whether enable cache. it’s cached by baseDir.
clean {Boolean}
Clean all logs directory, default is true.
If you are using ava, disable it.
app.mockLog([logger]) and app.expectLog(str[, logger]), app.notExpectLog(str[, logger])
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.
it('should work', async () => {
app.mockLog();
await app.httpRequest()
.get('/')
.expect('hello world')
.expect(200);
app.expectLog('foo in logger');
app.expectLog('foo in coreLogger', 'coreLogger');
app.expectLog('foo in myCustomLogger', 'myCustomLogger');
app.notExpectLog('bar in logger');
app.notExpectLog('bar in coreLogger', 'coreLogger');
app.notExpectLog('bar in myCustomLogger', 'myCustomLogger');
});
We also provide a bootstrap file for applications’ unit test to reduce duplicated code:
const { app, mock, assert } = require('egg-mock/bootstrap');
describe('test app', () => {
it('should request success', () => {
// mock data will be restored each case
mock.data(app, 'method', { foo: 'bar' });
return app.httpRequest()
.get('/foo')
.expect(res => {
assert(!res.headers.foo);
})
.expect(/bar/);
});
});
describe('test ctx', () => {
it('can use ctx', async function() {
const res = await this.ctx.service.foo();
assert(res === 'foo');
});
});
We inject ctx to every test case, so you can use app.currentContext in your test case.
and the first call of app.mockContext will reuse app.currentContext.
const { app, mock, assert } = require('egg-mock/bootstrap');
describe('test ctx', () => {
it('should can use ctx', () => {
const ctx = app.currentContext;
assert(ctx);
});
it('should reuse ctx', () => {
const ctx = app.currentContext;
// first call will reuse app.currentContext
const mockCtx = app.mockContext();
assert(ctx === mockCtx);
// next call will create a new context
// multi call app.mockContext will get wrong context with app.currentContext
// so we recommend to use app.mockContextScope
const mockCtx2 = app.mockContext();
assert(ctx !== mockCtx);
});
});
And if you use mm.app to bootstrap app, you can manually call setGetAppCallback,
then egg-mock will inject ctx for each test case.
egg-mock
Mock library for testing Egg applications, plugins and custom Egg frameworks with ease.
egg-mockinherits all APIs from node_modules/mm, offering more flexibility.Install
Usage
Create testcase
Launch a mock server with
mm.appRetrieve Agent instance through
app.agentaftermm.appstarted.Using
mm.clusterlaunch cluster server, you can use the same API asmm.app;Test Application
baseDiris optional that isprocess.cwd()by default.Test Framework
framework is optional, it’s
node_modules/eggby default.Test Plugin
If
eggPlugin.nameis defined inpackage.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.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.You can disable coverage, because it’s slow.
mm.env(env)
Mock env when starting
Environment list https://github.com/eggjs/egg-core/blob/master/lib/loader/egg_loader.js#L82
mm.consoleLevel(level)
Mock level that print to stdout/stderr
level list:
DEBUG,INFO,WARN,ERROR,NONEmm.home(homePath)
mock home directory
mm.restore()
restore all mock data, e.g.
afterEach(mm.restore)options
Options for
mm.appandmm.clusterbaseDir {String}
The directory of application, default is
process.cwd().You can use a string based on
$CWD/test/fixturesfor shortframework {String/Boolean}
The directory of framework
It can be true when test an framework
plugin
The directory of plugin, it’s detected automatically.
plugins {Object}
Define a list of plugins
cache {Boolean}
Determine whether enable cache. it’s cached by baseDir.
clean {Boolean}
Clean all logs directory, default is true.
If you are using
ava, disable it.app.mockLog([logger]) and app.expectLog(str[, logger]), app.notExpectLog(str[, logger])
Assert some string value in the logger instance. It is recommended to pair
app.mockLog()withapp.expectLog()orapp.notExpectLog(). Usingapp.expectLog()orapp.notExpectLog()alone requires dependency on the write speed of the log. When the server disk is high IO, unstable results will occur.app.httpRequest()
Request current app http server.
See supertest to get more APIs.
.unexpectHeader(name)
Assert current response not contains the specified header
.expectHeader(name)
Assert current response contains the specified header
app.mockContext(options)
app.mockContextScope(fn, options)
app.mockCookies(data)
app.mockHeaders(data)
Mock request header
app.mockSession(data)
app.mockService(service, methodName, fn)
app.mockServiceError(service, methodName, error)
You can mock an error for service
app.mockCsrf()
app.mockHttpclient(url, method, data)
Mock httpclient request, e.g.:
ctx.curlYou can also use Regular Expression for matching url.
You can alse mock agent.httpclient
Bootstrap
We also provide a bootstrap file for applications’ unit test to reduce duplicated code:
We inject ctx to every test case, so you can use
app.currentContextin your test case. and the first call ofapp.mockContextwill reuseapp.currentContext.And if you use mm.app to bootstrap app, you can manually call setGetAppCallback, then egg-mock will inject ctx for each test case.
env for custom bootstrap
EGG_BASE_DIR: the base dir of egg app EGG_FRAMEWORK: the framework of egg app
Questions & Suggestions
Please open an issue here.
License
MIT
Contributors
Made with contributors-img.