Skip to content

Commit

Permalink
feat: impl setGetAppCallback (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
killagu committed Jan 28, 2023
1 parent ccb28f5 commit b7d902c
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 13 deletions.
22 changes: 22 additions & 0 deletions README.md
Expand Up @@ -500,6 +500,28 @@ describe('test ctx', () => {
});
```

And if you use mm.app to bootstrap app, you can manually call setGetAppCallback,
then egg-mock will inject ctx for each test case.
```js
// test/.setup.js
const mm = require('egg-mock');
const path = require('path');
before(async function() {
const app = this.app = mm.app();
mm.setGetAppCallback(() => {
return app;
});
await app.ready();
});


// test/index.test.js
it('should work', function() {
// eslint-disable-next-line no-undef
assert(this.app.currentContext);
});
```

### env for custom bootstrap
EGG_BASE_DIR: the base dir of egg app
EGG_FRAMEWORK: the framework of egg app
Expand Down
2 changes: 1 addition & 1 deletion bootstrap.js
Expand Up @@ -16,7 +16,7 @@ appHandler.setupApp();
module.exports = {
assert,
get app() {
return appHandler.getApp();
return appHandler.getBootstrapApp();
},
mock,
mm: mock,
Expand Down
9 changes: 9 additions & 0 deletions index.d.ts
Expand Up @@ -2,6 +2,7 @@ import { Application, Context, EggLogger } from 'egg';
import { MockMate } from 'mm';
import { Test } from 'supertest';
import { MockAgent } from 'urllib';
import { Suite } from 'mocha';

export { MockAgent };
interface EggTest extends Test {
Expand Down Expand Up @@ -155,6 +156,14 @@ export interface EggMock extends MockMate {
* restore mock
*/
restore: () => any;

/**
* If you use mm.app instead of egg-mock/bootstrap to bootstrap app.
* Should manually call setGetAppCallback,
* then egg-mock will inject ctx for each test case
* @param cb
*/
setGetAppCallback: (cb: (suite: Suite) => Promise<MockApplication> ) => void;
}

declare const mm: EggMock;
Expand Down
2 changes: 2 additions & 0 deletions index.js
Expand Up @@ -75,6 +75,8 @@ Object.assign(mock, mm, {
mm(process.env, 'EGG_HOME', homePath);
}
},

setGetAppCallback: require('./lib/app_handler').setGetAppCallback,
});

process.setMaxListeners(100);
Expand Down
1 change: 1 addition & 0 deletions lib/app.js
Expand Up @@ -29,6 +29,7 @@ const MOCK_APP_METHOD = [
'_app',
'on',
'once',
'then',
];

class MockApplication extends EventEmitter {
Expand Down
15 changes: 14 additions & 1 deletion lib/app_handler.js
Expand Up @@ -37,6 +37,19 @@ exports.setupApp = () => {
}
};

exports.getApp = () => {
let getAppCallback;

exports.setGetAppCallback = cb => {
getAppCallback = cb;
};

exports.getApp = async suite => {
if (getAppCallback) {
return getAppCallback(suite);
}
return app;
};

exports.getBootstrapApp = () => {
return app;
};
15 changes: 9 additions & 6 deletions lib/inject_context.js
Expand Up @@ -5,7 +5,7 @@ const EGG_CONTEXT = Symbol.for('mocha#suite#ctx#eggCtx');
/**
* Monkey patch the mocha instance with egg context.
*
* @param {Function} mocha
* @param {Function} mocha -
*/
function injectContext(mocha) {
if (!mocha || mocha._injectContextLoaded) {
Expand All @@ -19,7 +19,7 @@ function injectContext(mocha) {
// Inject ctx for before/after.
Runner.prototype.runSuite = async function(suite, fn) {
debug('run suite: %s %b', suite.title, !!(suite.ctx && suite[EGG_CONTEXT]));
const app = appHandler.getApp();
const app = await appHandler.getApp(suite);
const self = this;
if (!app) {
return runSuite.call(self, suite, fn);
Expand All @@ -46,8 +46,8 @@ function injectContext(mocha) {

// Inject ctx for beforeEach/it/afterEach.
// And ctx with before/after is not same as beforeEach/it/afterEach.
Runner.prototype.runTests = function(suite, fn) {
const app = appHandler.getApp();
Runner.prototype.runTests = async function(suite, fn) {
const app = await appHandler.getApp(suite);
const self = this;
if (!app) {
return runTests.call(self, suite, fn);
Expand All @@ -67,6 +67,7 @@ function injectContext(mocha) {
}
suite.tests = [ test ];

const app = await appHandler.getApp(suite);
await app.ready();
const mockContextFun = app.mockModuleContextScope || app.mockContextScope;
try {
Expand All @@ -80,8 +81,10 @@ function injectContext(mocha) {
});
});
});
} catch (errSuite) {
return done(errSuite);
} catch (err) {
err.message = '[egg-mock] run mock context error: ' + err.message;
console.error(err);
return done(suite);
}
return next(i + 1);
}
Expand Down
10 changes: 5 additions & 5 deletions register.js
Expand Up @@ -18,15 +18,15 @@ exports.mochaGlobalTeardown = async () => {

exports.mochaHooks = {
async beforeAll() {
const app = appHandler.getApp();
const app = await appHandler.getApp();
debug('mochaHooks.beforeAll call, _app: %s', app);

if (app) {
await app.ready();
}
},
async afterEach() {
const app = appHandler.getApp();
const app = await appHandler.getApp();
debug('mochaHooks.afterEach call, _app: %s', app);
if (app) {
await app.backgroundTasksFinished();
Expand All @@ -40,15 +40,15 @@ exports.mochaHooks = {
*
* @return {Array}
*/
function findNodeJSMocha () {
function findNodeJSMocha() {
const children = require.cache || {};

return Object.keys(children)
.filter(function (child) {
.filter(function(child) {
const val = children[child].exports;
return typeof val === 'function' && val.name === 'Mocha';
})
.map(function (child) {
.map(function(child) {
return children[child].exports;
});
}
Expand Down
5 changes: 5 additions & 0 deletions test/fixtures/setup-app/config/config.default.js
@@ -0,0 +1,5 @@
'use strict';

module.exports = {
keys: '123',
};
3 changes: 3 additions & 0 deletions test/fixtures/setup-app/package.json
@@ -0,0 +1,3 @@
{
"name": "app"
}
12 changes: 12 additions & 0 deletions test/fixtures/setup-app/test/.setup.js
@@ -0,0 +1,12 @@
const mm = require('../../../../index');
const path = require('path');
before(async () => {
global.app = mm.app({
baseDir: path.join(__dirname, '../'),
framework: require.resolve('egg'),
});
mm.setGetAppCallback(() => {
return global.app;
});
await global.app.ready();
});
8 changes: 8 additions & 0 deletions test/fixtures/setup-app/test/index.test.js
@@ -0,0 +1,8 @@
const assert = require('assert');

describe('test/index.test.ts', () => {
it('should work', () => {
// eslint-disable-next-line no-undef
assert(app.currentContext);
});
});
16 changes: 16 additions & 0 deletions test/inject_ctx.test.js
Expand Up @@ -20,4 +20,20 @@ describe('test/inject_ctx.test.js', () => {
.expect('stdout', /9 passing/)
.end();
});

it('should inject ctx to runner with setGetAppCallback', async () => {
const fixture = path.join(__dirname, 'fixtures/setup-app');

await coffee.fork(require.resolve('egg-bin/bin/egg-bin'), [
'test',
'-r', require.resolve('../register'),
'--full-trace',
], {
cwd: fixture,
})
.debug()
.expect('code', 0)
// .expect('stdout', /9 passing/)
.end();
});
});

0 comments on commit b7d902c

Please sign in to comment.