Skip to content

Commit

Permalink
fix: every it should has self ctx (#150)
Browse files Browse the repository at this point in the history
  • Loading branch information
killagu committed Jan 18, 2023
1 parent 4d44689 commit bf33c1c
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
51 changes: 50 additions & 1 deletion lib/inject_context.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ function injectContext(mocha) {

const Runner = mocha.Runner;
const runSuite = Runner.prototype.runSuite;
const runTests = Runner.prototype.runTests;

// 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();
Expand All @@ -28,7 +30,6 @@ function injectContext(mocha) {
const mockContextFun = app.mockModuleContextScope || app.mockContextScope;
await mockContextFun.call(app, async function(eggCtx) {
suite.ctx[EGG_CONTEXT] = eggCtx;
eggCtx.mochaTitle = suite.title;
await new Promise(resolve => {
runSuite.call(self, suite, aErrSuite => {
errSuite = aErrSuite;
Expand All @@ -43,6 +44,54 @@ function injectContext(mocha) {
return fn(errSuite);
};

// 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();
const self = this;
if (!app) {
return runTests.call(self, suite, fn);
}

const tests = suite.tests.slice();

function done(errSuite) {
suite.tests = tests;
return fn(errSuite);
}

async function next(i) {
const test = tests[i];
if (!test) {
return done();
}
suite.tests = [ test ];

await app.ready();
const mockContextFun = app.mockModuleContextScope || app.mockContextScope;
try {
await mockContextFun.call(app, async function() {
await new Promise((resolve, reject) => {
runTests.call(self, suite, errSuite => {
if (errSuite) {
return reject(errSuite);
}
return resolve();
});
});
});
} catch (errSuite) {
return done(errSuite);
}
return next(i + 1);
}
next(0).catch(e => {
e.message = '[egg-mock] inject context error: ' + e.message;
console.error(e);
done(suite);
});
};

mocha._injectContextLoaded = true;
}

Expand Down
3 changes: 2 additions & 1 deletion test/fixtures/tegg-app/test/hooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe('test/hooks.test.ts', () => {
after(() => {
afterCtx = app.currentContext;
assert(beforeCtx);
assert(beforeCtx !== itCtxList['foo']);
assert(itCtxList['foo'] !== itCtxList['bar']);
assert(afterCtx === beforeCtx);
assert(beforeEachCtxList['foo'] === afterEachCtxList['foo']);
Expand Down Expand Up @@ -62,7 +63,7 @@ describe('test/hooks.test.ts', () => {
});

after(() => {
assert(itCtxList[0] === itCtxList[1]);
assert(itCtxList[0] !== itCtxList[1]);
})
});
});

0 comments on commit bf33c1c

Please sign in to comment.