Skip to content

Commit

Permalink
jest-haste-map: mock 'fs' with more idiomatic jest.mock() (jestjs#4046)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeanlauliac authored and cpojer committed Jul 17, 2017
1 parent 17bde04 commit b07c035
Showing 1 changed file with 28 additions and 29 deletions.
57 changes: 28 additions & 29 deletions packages/jest-haste-map/src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,34 @@ jest.mock('sane', () => {
};
});

let mockChangedFiles;
let mockFs;

jest.mock('graceful-fs', () => ({
readFileSync: jest.fn((path, options) => {
expect(options).toBe('utf8');

// A file change can be triggered by writing into the
// mockChangedFiles object.
if (mockChangedFiles && path in mockChangedFiles) {
return mockChangedFiles[path];
}

if (mockFs[path]) {
return mockFs[path];
}

const error = new Error(`Cannot read path '${path}'.`);
error.code = 'ENOENT';
throw error;
}),
writeFileSync: jest.fn((path, data, options) => {
expect(options).toBe('utf8');
mockFs[path] = data;
}),
}));
jest.mock('fs', () => require('graceful-fs'));

const skipOnWindows = require('skipOnWindows');

const cacheFilePath = '/cache-file';
Expand All @@ -68,14 +96,10 @@ let defaultConfig;
let fs;
let H;
let HasteMap;
let mockChangedFiles;
let mockClocks;
let mockEmitters;
let mockFs;
let object;
let readFileSync;
let workerFarmMock;
let writeFileSync;

describe('HasteMap', () => {
skipOnWindows.suite();
Expand Down Expand Up @@ -121,29 +145,6 @@ describe('HasteMap', () => {
mockChangedFiles = null;

fs = require('graceful-fs');
readFileSync = fs.readFileSync;
writeFileSync = fs.writeFileSync;
fs.readFileSync = jest.fn((path, options) => {
expect(options).toBe('utf8');

// A file change can be triggered by writing into the
// mockChangedFiles object.
if (mockChangedFiles && path in mockChangedFiles) {
return mockChangedFiles[path];
}

if (mockFs[path]) {
return mockFs[path];
}

const error = new Error(`Cannot read path '${path}'.`);
error.code = 'ENOENT';
throw error;
});
fs.writeFileSync = jest.fn((path, data, options) => {
expect(options).toBe('utf8');
mockFs[path] = data;
});

consoleWarn = console.warn;
console.warn = jest.fn();
Expand All @@ -167,8 +168,6 @@ describe('HasteMap', () => {

afterEach(() => {
console.warn = consoleWarn;
fs.readFileSync = readFileSync;
fs.writeFileSync = writeFileSync;
});

it('exports constants', () => {
Expand Down

0 comments on commit b07c035

Please sign in to comment.