Jean Lauliac e327f88f02 react-native: make automated fs-based tests platform-independent
Summary:
@public

These tests are using a mock memory FS to start with, so there is no reason at all they should depend on the host OS or filesystem details. This changeset fixes that so that we fully mock the `fs` and `path` modules dependending on the mock platform (not the host platform). I also added an example of how we can test both platforms (regardless of the host platform) in `findPackageClassName`. Follow up changeset will be to do the same for all the other affected tests.

Related to https://github.com/facebook/react-native/issues/20260.

Reviewed By: mjesun

Differential Revision: D9771024

fbshipit-source-id: b368b43e8e54292d33b6183eec9a9ea69f2e6e76
2018-09-17 05:46:47 -07:00

62 lines
1.4 KiB
JavaScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const path = require('path');
const MemoryFS = require('metro-memory-fs');
let fs;
function setMockFilesystem(object, platform) {
reset(platform);
const root = platform === 'win32' ? 'c:\\' : '/';
mockDir(root, {...object});
return root;
}
function mockDir(dirPath, desc) {
for (const entName in desc) {
const ent = desc[entName];
const entPath = path.join(dirPath, entName);
if (typeof ent === 'string' || ent instanceof Buffer) {
fs.writeFileSync(entPath, ent);
continue;
}
if (typeof ent !== 'object') {
throw new Error(require('util').format('invalid entity:', ent));
}
if (ent.SYMLINK != null) {
fs.symlinkSync(ent.SYMLINK, entPath);
continue;
}
fs.mkdirSync(entPath);
mockDir(entPath, ent);
}
}
function reset(platform) {
if (path.mock == null) {
throw new Error(
'to use this "fs" module mock, you must also mock the "path" module',
);
}
path.mock.reset(platform);
const cwd = () => (platform === 'win32' ? 'c:\\' : '/');
fs = new MemoryFS({platform, cwd});
Object.assign(mockFs, fs);
}
const mockFs = {};
mockFs.__setMockFilesystem = setMockFilesystem;
mockFs.mock = {clear: reset};
reset('posix');
module.exports = mockFs;