Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest-haste-map: mock 'fs' with more idiomatic jest.mock() #4046

Merged
merged 1 commit into from
Jul 17, 2017
Merged
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
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