RN: add some test to module system

Reviewed By: davidaurelio

Differential Revision: D5862757

fbshipit-source-id: cf5c88c4bb9d65368df07f6e85b207c90565bad9
This commit is contained in:
Jean Lauliac 2017-09-20 10:51:24 -07:00 committed by Facebook Github Bot
parent 7d92dd2b5d
commit 39238acb78
1 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,94 @@
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+javascript_foundation
* @format
*/
'use strict';
const babel = require('babel-core');
const babelConfig = require('../../../babelRegisterOnly').config;
const fs = require('fs');
describe('require', () => {
const moduleSystemCode = (() => {
const {only, ...config} = babelConfig([]);
only;
const rawCode = fs.readFileSync(require.resolve('../require'), 'utf8');
return babel.transform(rawCode, config).code;
})();
// eslint-disable-next-line no-new-func
const createModuleSystem = new Function(
'global',
'__DEV__',
moduleSystemCode,
);
let moduleSystem;
beforeEach(() => {
moduleSystem = {};
});
it('works with plain bundles', () => {
createModuleSystem(moduleSystem, false);
expect(moduleSystem.require).not.toBeUndefined();
expect(moduleSystem.__d).not.toBeUndefined();
const mockExports = {foo: 'bar'};
const mockFactory = jest
.fn()
.mockImplementation(
(global, require, moduleObject, exports, dependencyMap) => {
moduleObject.exports = mockExports;
},
);
moduleSystem.__d(mockFactory, 1, [2, 3]);
expect(mockFactory).not.toBeCalled();
const m = moduleSystem.require(1);
expect(mockFactory.mock.calls.length).toBe(1);
expect(mockFactory.mock.calls[0][0]).toBe(moduleSystem);
expect(m).toBe(mockExports);
expect(mockFactory.mock.calls[0][4]).toEqual([2, 3]);
});
it('works with Random Access Modules (RAM) bundles', () => {
const mockExports = {foo: 'bar'};
const mockFactory = jest
.fn()
.mockImplementation(
(global, require, moduleObject, exports, dependencyMap) => {
moduleObject.exports = mockExports;
},
);
moduleSystem.nativeRequire = jest.fn().mockImplementation(moduleId => {
moduleSystem.__d(mockFactory, moduleId, [2, 3]);
});
createModuleSystem(moduleSystem, false);
expect(moduleSystem.require).not.toBeUndefined();
expect(moduleSystem.__d).not.toBeUndefined();
expect(moduleSystem.nativeRequire).not.toBeCalled();
expect(mockFactory).not.toBeCalled();
const m = moduleSystem.require(1);
expect(moduleSystem.nativeRequire.mock.calls.length).toBe(1);
expect(moduleSystem.nativeRequire).toBeCalledWith(1);
expect(mockFactory.mock.calls.length).toBe(1);
expect(mockFactory.mock.calls[0][0]).toBe(moduleSystem);
expect(m).toBe(mockExports);
expect(mockFactory.mock.calls[0][4]).toEqual([2, 3]);
});
});