Skip to content

Commit

Permalink
test: add tests for finding libraries from react-native.config.js
Browse files Browse the repository at this point in the history
  • Loading branch information
satya164 committed Sep 6, 2022
1 parent eb57ab0 commit 357bbbc
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 43 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
"devDependencies": {
"flow-bin": "^0.186.0",
"hermes-eslint": "0.8.0",
"mock-fs": "^5.1.4",
"react": "18.2.0",
"react-test-renderer": "^18.2.0"
},
Expand Down
146 changes: 108 additions & 38 deletions scripts/codegen/__tests__/generate-artifacts-executor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,19 @@
const underTest = require('../generate-artifacts-executor');
const fixtures = require('../__test_fixtures__/fixtures');
const path = require('path');
const fs = require('fs');
const child_process = require('child_process');

const codegenConfigKey = 'codegenConfig';
const reactNativeDependencyName = 'react-native';
const rootPath = path.join(__dirname, '../../..');

describe('generateCode', () => {
afterEach(() => {
jest.resetModules();
jest.resetAllMocks();
});

it('executeNodes with the right arguments', () => {
// Define variables and expected values
const iosOutputDir = 'app/ios/build/generated/ios';
Expand All @@ -32,46 +39,32 @@ describe('generateCode', () => {
const tmpOutDir = path.join(tmpDir, 'out');

// mock used functions
let mkdirSyncInvocationCount = 0;
jest.mock('fs', () => ({
mkdirSync: (location, config) => {
if (mkdirSyncInvocationCount === 0) {
expect(location).toEqual(tmpOutDir);
}
if (mkdirSyncInvocationCount === 1) {
expect(location).toEqual(iosOutputDir);
}

mkdirSyncInvocationCount += 1;
},
}));

let execSyncInvocationCount = 0;
jest.mock('child_process', () => ({
execSync: command => {
if (execSyncInvocationCount === 0) {
const expectedCommand = `${node} ${path.join(
rnRoot,
'generate-specs-cli.js',
)} \
--platform ios \
--schemaPath ${pathToSchema} \
--outputDir ${tmpOutDir} \
--libraryName ${library.config.name} \
--libraryType ${libraryType}`;
expect(command).toEqual(expectedCommand);
}

if (execSyncInvocationCount === 1) {
expect(command).toEqual(`cp -R ${tmpOutDir}/* ${iosOutputDir}`);
}

execSyncInvocationCount += 1;
},
}));
jest.spyOn(fs, 'mkdirSync').mockImplementation();
jest.spyOn(child_process, 'execSync').mockImplementation();

underTest._generateCode(iosOutputDir, library, tmpDir, node, pathToSchema);
expect(mkdirSyncInvocationCount).toBe(2);

const expectedCommand = `${node} ${path.join(
rnRoot,
'generate-specs-cli.js',
)} --platform ios --schemaPath ${pathToSchema} --outputDir ${tmpOutDir} --libraryName ${
library.config.name
} --libraryType ${libraryType}`;

expect(child_process.execSync).toHaveBeenCalledTimes(2);
expect(child_process.execSync).toHaveBeenNthCalledWith(1, expectedCommand);
expect(child_process.execSync).toHaveBeenNthCalledWith(
2,
`cp -R ${tmpOutDir}/* ${iosOutputDir}`,
);

expect(fs.mkdirSync).toHaveBeenCalledTimes(2);
expect(fs.mkdirSync).toHaveBeenNthCalledWith(1, tmpOutDir, {
recursive: true,
});
expect(fs.mkdirSync).toHaveBeenNthCalledWith(2, iosOutputDir, {
recursive: true,
});
});
});

Expand Down Expand Up @@ -202,6 +195,83 @@ describe('extractLibrariesFromJSON', () => {
});
});

describe('findCodegenEnabledLibraries', () => {
const mock = require('mock-fs');
const {
_findCodegenEnabledLibraries: findCodegenEnabledLibraries,
} = require('../generate-artifacts-executor');

afterEach(() => {
mock.restore();
});

it('returns libraries defined in react-native.config.js', () => {
const projectDir = path.join(__dirname, '../../../../test-project');
const baseCodegenConfigFileDir = path.join(__dirname, '../../..');
const baseCodegenConfigFilePath = path.join(
baseCodegenConfigFileDir,
'package.json',
);

mock({
[baseCodegenConfigFilePath]: `
{
"codegenConfig": {}
}
`,
[projectDir]: {
app: {
'package.json': `{
"name": "my-app"
}`,
'react-native.config.js': '',
},
'library-foo': {
'package.json': `{
"name": "react-native-foo",
"codegenConfig": {
"name": "RNFooSpec",
"type": "modules",
"jsSrcsDir": "src"
}
}`,
},
},
});

jest.mock(path.join(projectDir, 'app', 'react-native.config.js'), () => ({
dependencies: {
'react-native-foo': {
root: path.join(projectDir, 'library-foo'),
},
'react-native-bar': {
root: path.join(projectDir, 'library-bar'),
},
},
}));

const libraries = findCodegenEnabledLibraries(
`${projectDir}/app`,
baseCodegenConfigFileDir,
`package.json`,
'codegenConfig',
);

expect(libraries).toEqual([
{
library: 'react-native',
config: {},
libraryPath: baseCodegenConfigFileDir,
},
{
library: 'react-native-foo',
config: {name: 'RNFooSpec', type: 'modules', jsSrcsDir: 'src'},
libraryPath: path.join(projectDir, 'library-foo'),
},
]);
});
});

describe('delete empty files and folders', () => {
beforeEach(() => {
jest.resetModules();
Expand Down
23 changes: 18 additions & 5 deletions scripts/codegen/generate-artifacts-executor.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,8 @@ function handleLibrariesFromReactNativeConfig(
const rnConfig = require(rnConfigFilePath);

if (rnConfig.dependencies != null) {
Object.keys(rnConfig.dependencies).forEach(dependencyName => {
const dependencyConfig = rnConfig.dependencies[dependencyName];
Object.keys(rnConfig.dependencies).forEach(name => {
const dependencyConfig = rnConfig.dependencies[name];

if (dependencyConfig.root) {
const codegenConfigFileDir = path.resolve(
Expand All @@ -234,14 +234,16 @@ function handleLibrariesFromReactNativeConfig(
codegenConfigFileDir,
codegenConfigFilename,
);
const pkgJsonPath = path.join(codegenConfigFileDir, 'package.json');

if (fs.existsSync(configFilePath)) {
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath));
const configFile = JSON.parse(fs.readFileSync(configFilePath));
extractLibrariesFromJSON(
configFile,
libraries,
codegenConfigKey,
dependencyName,
pkgJson.name,
codegenConfigFileDir,
);
}
Expand Down Expand Up @@ -409,7 +411,12 @@ function createComponentProvider(
}
}

function findCodegenEnabledLibraries(appRootDir) {
function findCodegenEnabledLibraries(
appRootDir,
baseCodegenConfigFileDir,
codegenConfigFilename,
codegenConfigKey,
) {
const pkgJson = readPackageJSON(appRootDir);
const dependencies = {...pkgJson.dependencies, ...pkgJson.devDependencies};
const libraries = [];
Expand Down Expand Up @@ -504,7 +511,12 @@ function execute(
}

try {
const libraries = findCodegenEnabledLibraries(appRootDir);
const libraries = findCodegenEnabledLibraries(
appRootDir,
baseCodegenConfigFileDir,
codegenConfigFilename,
codegenConfigKey,
);

if (libraries.length === 0) {
console.log('[Codegen] No codegen-enabled libraries found.');
Expand Down Expand Up @@ -541,6 +553,7 @@ module.exports = {
execute: execute,
// exported for testing purposes only:
_extractLibrariesFromJSON: extractLibrariesFromJSON,
_findCodegenEnabledLibraries: findCodegenEnabledLibraries,
_executeNodeScript: executeNodeScript,
_generateCode: generateCode,
_cleanupEmptyFilesAndFolders: cleanupEmptyFilesAndFolders,
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5301,6 +5301,11 @@ mkdirp@^0.5.1:
dependencies:
minimist "0.0.8"

mock-fs@^5.1.4:
version "5.1.4"
resolved "https://registry.yarnpkg.com/mock-fs/-/mock-fs-5.1.4.tgz#d64dc37b2793613ca7148b510b1167b5b8afb6b8"
integrity sha512-sudhLjCjX37qWIcAlIv1OnAxB2wI4EmXByVuUjILh1rKGNGpGU8GNnzw+EAbrhdpBe0TL/KONbK1y3RXZk8SxQ==

ms@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
Expand Down

0 comments on commit 357bbbc

Please # to comment.