Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/testlab/src/test-sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ export class TestSandbox {
*/
async reset(): Promise<void> {
this.validateInst();

// Decache files from require's cache so future tests aren't affected incase
// a file is recreated in sandbox with the same file name but different
// contents after resetting the sandbox.
for (const key in require.cache) {
if (key.startsWith(this.path)) {
Copy link
Member

@bajtos bajtos Jun 5, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we check that the key starts with this.path + '/' to ensure we don't accidentally decache file names like sandbox-123/file.js or sandbox.bak/file.js when this.path = 'sandbox'? (Plus handle \ on Windows.)

Not a big deal, maybe fixing this edge case is not worth the implementation complexity.

delete require.cache[key];
}
}

await emptyDir(this.path);
}

Expand Down
21 changes: 20 additions & 1 deletion packages/testlab/test/integration/test-sandbox.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import {TestSandbox, expect} from '../..';
import {resolve} from 'path';
import {remove, pathExists, readFile} from 'fs-extra';
import {remove, pathExists, readFile, writeJSON} from 'fs-extra';

describe('TestSandbox integration tests', () => {
let sandbox: TestSandbox;
Expand Down Expand Up @@ -63,6 +63,25 @@ describe('TestSandbox integration tests', () => {
expect(fileContents.pop()).to.equal(sourceMapString);
});

it('resets the sandbox', async () => {
const file = 'test.js';
const resolvedFile = resolve(__dirname, '../fixtures/test.js');
await sandbox.copyFile(resolvedFile);
await sandbox.reset();
expect(await pathExists(resolve(path, file))).to.be.False();
});

it('decaches files from npm require when sandbox is reset', async () => {
const file = 'test.json';
await writeJSON(resolve(path, file), {x: 1});
const data = require(resolve(path, file));
expect(data).to.be.eql({x: 1});
await sandbox.reset();
await writeJSON(resolve(path, file), {x: 2});
const data2 = require(resolve(path, file));
expect(data2).to.be.eql({x: 2});
});

it('deletes the test sandbox', async () => {
await sandbox.delete();
expect(await pathExists(path)).to.be.False();
Expand Down