From cf48f99b6f5f1f1a7999d069e7b554cb0388f207 Mon Sep 17 00:00:00 2001 From: Jean Lauliac Date: Mon, 17 Jul 2017 16:10:52 +0100 Subject: [PATCH] jest-haste-map: mock 'fs' with more idiomatic jest.mock() --- .../src/__tests__/index.test.js | 57 +++++++++---------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index 455671780cdb..9e856abdd851 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -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'; @@ -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(); @@ -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(); @@ -167,8 +168,6 @@ describe('HasteMap', () => { afterEach(() => { console.warn = consoleWarn; - fs.readFileSync = readFileSync; - fs.writeFileSync = writeFileSync; }); it('exports constants', () => {