Skip to content

Commit

Permalink
fix: should run restore in the current event loop (#172)
Browse files Browse the repository at this point in the history
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Refactor**
- Improved performance of the `restore` method by executing tasks in
parallel.

- **Tests**
- Enhanced test suite with refined import statements, better assertion
methods, and a new test case for asynchronous behavior.
- Introduced a `sleep` function for testing asynchronous code execution.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
fengmk2 authored Jul 5, 2024
1 parent 22ba637 commit 1f9fc01
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
3 changes: 1 addition & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ module.exports.default = mock;
Object.assign(mock, mm, {
async restore() {
cluster.restore();
await mockAgent.restore();
return await mm.restore();
await Promise.all([ mockAgent.restore(), mm.restore() ]);
},

/**
Expand Down
38 changes: 30 additions & 8 deletions test/mock_env.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
'use strict';

const path = require('path');
const assert = require('assert');
const path = require('node:path');
const { strict: assert } = require('node:assert');
const mm = require('..');

const fixtures = path.join(__dirname, 'fixtures');

describe('test/mock_env.test.js', () => {

let app;
before(() => {
app = mm.app({
Expand All @@ -17,9 +15,33 @@ describe('test/mock_env.test.js', () => {
after(() => app.close());
afterEach(mm.restore);

it('should mock env succes', () => {
it('should mock env success', () => {
app.mockEnv('prod');
assert(app.config.env === 'prod');
assert(app.config.serverEnv === 'prod');
assert.equal(app.config.env, 'prod');
assert.equal(app.config.serverEnv, 'prod');
});

it('should keep mm.restore execute in the current event loop', async () => {
mm.restore();
assert.equal(app.config.env, 'unittest');
assert.equal(app.config.serverEnv, undefined);

app.mockEnv('prod');
assert.equal(app.config.env, 'prod');
assert.equal(app.config.serverEnv, 'prod');

await sleep(1);
assert.equal(app.config.env, 'prod');
assert.equal(app.config.serverEnv, 'prod');

mm.restore();
assert.equal(app.config.env, 'unittest');
assert.equal(app.config.serverEnv, undefined);
});
});

function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}

0 comments on commit 1f9fc01

Please sign in to comment.