Skip to content

Commit 732420c

Browse files
Run Fantom tests written in TypeScript (#60087)
Fantom recognized its test files in two places, its Jest config's testRegex and the Babel plugin that starts each test with `debugger;`, and both took only -itest.js and -itest.fb.js. config/fantomTestFiles.js now holds one pattern, which also takes -itest.ts and -itest.tsx, with or without .fb, and the name the runner's multi-config titles show. Jest, the plugin and the runner use it, and the Metro transformer's cache key includes it. The plugin reads a Windows path with its separators turned to `/`, and still skips the entrypoints the runner generates in .out, which are named after their tests. The plugin, which now imports the shared pattern, is typed like the preset's inline-platform-plugin.js, so its new strict-local test and the Metro transformer import it without an untyped-import suppression. FantomTypeScript-itest.tsx, which uses satisfies so that it compiles only as TypeScript, keeps a TypeScript test running.
1 parent f559f3c commit 732420c

9 files changed

Lines changed: 239 additions & 21 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ Architecture notes live in `__docs__` directories beside the code they describe,
3131
| Command | Purpose |
3232
| --- | --- |
3333
| `yarn test <path>` | Jest tests, found in `__tests__` directories and named `*-test.js` |
34-
| `yarn fantom <path>` | [Fantom](private/react-native-fantom/__docs__/README.md) integration tests, named `*-itest.js` — builds a native tester on first run |
34+
| `yarn fantom <path>` | [Fantom](private/react-native-fantom/__docs__/README.md) integration tests, named `*-itest.js`, `*-itest.ts` or `*-itest.tsx` — builds a native tester on first run |
3535
| `yarn lint` | ESLint (`--max-warnings 0`) |
3636
| `yarn flow-check` | Flow |
3737
| `yarn format` | Format JavaScript/TypeScript, C/C++/Objective-C/protobuf, Kotlin, Java, Python, and Swift sources |

‎private/react-native-fantom/__docs__/README.md‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,9 @@ Use regular Jest for:
7575

7676
## 🚀 Usage
7777

78-
Create a file with the `-itest.js` suffix anywhere you would normally create a
79-
Jest unit test file.
78+
Create a file with the `-itest.js` suffix, or `-itest.ts` or `-itest.tsx` for a
79+
test written in TypeScript, anywhere you would normally create a Jest unit test
80+
file.
8081

8182
The high level structure of Fantom tests is similar to Jest unit tests. However,
8283
only a subset of Jest's Global API is currently available. For example,
@@ -267,7 +268,8 @@ hi
267268
that limitation. Prefer a short comment explaining why the internal access
268269
is necessary.
269270
- Place test files in `__tests__` directories alongside the code being tested.
270-
- Benchmark tests use the `-benchmark-itest.js` suffix.
271+
- Benchmark tests use the `-benchmark-itest.js`, `-benchmark-itest.ts` or
272+
`-benchmark-itest.tsx` suffix.
271273
- Use `Fantom.runTask()` to render and run synchronous operations; it ensures
272274
the React work is flushed before assertions.
273275
- Access elements through refs and use `nullthrows` for type-safe access to the
@@ -682,9 +684,10 @@ change this.
682684

683685
#### Where can I find examples of tests?
684686

685-
Look for files with the `-itest.js` suffix to find existing tests. The Fantom
686-
test for its public API ([`Fantom-itest.js`](../src/__tests__/Fantom-itest.js))
687-
has simple examples you can learn from.
687+
Look for files with the `-itest.js`, `-itest.ts` or `-itest.tsx` suffix to find
688+
existing tests. The Fantom test for its public API
689+
([`Fantom-itest.js`](../src/__tests__/Fantom-itest.js)) has simple examples you
690+
can learn from.
688691

689692
#### Are tests executed on Github CI?
690693

@@ -750,8 +753,8 @@ Fantom tests are meant to be written, executed and reported as regular Jests
750753
tests. To accomplish that, **Fantom is implemented as a Jest test runner**.
751754

752755
Fantom provides a [Jest configuration](../config/jest.config.js) to use
753-
[its runner](../runner/runner.js) for any tests matching the `-itest.js` suffix
754-
within the repository.
756+
[its runner](../runner/runner.js) for any tests matching the `-itest.js`,
757+
`-itest.ts` or `-itest.tsx` suffix within the repository.
755758

756759
When Jest runs, for every file that matches that configuration, it calls into
757760
the Fantom runner, which receives the path to the test file along with different
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow strict-local
8+
* @format
9+
*/
10+
11+
'use strict';
12+
13+
const injectDebuggerStatementsInTests = require('../babel-plugins/inject-debugger-statements-in-tests');
14+
const {getFantomTestName} = require('../fantomTestFiles');
15+
const fantomJestConfig = require('../jest.config');
16+
const {transformSync} = require('@babel/core');
17+
const path = require('node:path');
18+
19+
const FANTOM_TEST_PATHS = [
20+
'Libraries/Components/View/__tests__/View-itest.js',
21+
'Libraries/Components/View/__tests__/View-itest.fb.js',
22+
'my-library/__tests__/Example-itest.ts',
23+
'my-library/__tests__/Example-itest.tsx',
24+
'my-library/__tests__/Example-itest.fb.ts',
25+
'my-library/__tests__/Example-itest.fb.tsx',
26+
];
27+
28+
const GENERATED_ENTRYPOINT_PATH =
29+
'private/react-native-fantom/.out/js-builds/run-1/1700000000000-View-itest.js';
30+
31+
const OTHER_PATHS = [
32+
'Libraries/Components/View/__tests__/View-test.js',
33+
'my-library/__tests__/Example-itest.jsx',
34+
'my-library/__tests__/Example-itest.d.ts',
35+
'Libraries/Components/View/View-itest.js',
36+
GENERATED_ENTRYPOINT_PATH,
37+
];
38+
39+
const testRegex = new RegExp(fantomJestConfig.testRegex);
40+
41+
function isRunByJest(testPath: string): boolean {
42+
return (
43+
fantomJestConfig.moduleFileExtensions.includes(
44+
path.extname(testPath).slice(1),
45+
) && testRegex.test(testPath)
46+
);
47+
}
48+
49+
function onWindows(testPath: string): string {
50+
return `C:\\repository\\${testPath.replaceAll('/', '\\')}`;
51+
}
52+
53+
function transformTestFile(filename: string, code: string): ?string {
54+
return transformSync(code, {
55+
babelrc: false,
56+
configFile: false,
57+
filename,
58+
plugins: [injectDebuggerStatementsInTests],
59+
})?.code;
60+
}
61+
62+
describe('Fantom test files', () => {
63+
it.each(FANTOM_TEST_PATHS)('Jest runs %s', testPath => {
64+
expect(isRunByJest(`/repository/${testPath}`)).toBe(true);
65+
});
66+
67+
it.each(OTHER_PATHS)('Jest skips %s', testPath => {
68+
expect(isRunByJest(`/repository/${testPath}`)).toBe(false);
69+
});
70+
71+
it.each(FANTOM_TEST_PATHS)(
72+
'starts %s with a debugger statement, once',
73+
testPath => {
74+
const transformed = transformTestFile(
75+
`/repository/${testPath}`,
76+
'run();',
77+
);
78+
79+
expect(transformed).toBe('debugger;\nrun();');
80+
expect(
81+
transformTestFile(`/repository/${testPath}`, transformed ?? ''),
82+
).toBe(transformed);
83+
},
84+
);
85+
86+
it.each(OTHER_PATHS)('leaves %s without a debugger statement', testPath => {
87+
expect(transformTestFile(`/repository/${testPath}`, 'run();')).toBe(
88+
'run();',
89+
);
90+
});
91+
92+
it.each(FANTOM_TEST_PATHS)(
93+
'starts %s with a debugger statement on a Windows path',
94+
testPath => {
95+
expect(transformTestFile(onWindows(testPath), 'run();')).toBe(
96+
'debugger;\nrun();',
97+
);
98+
},
99+
);
100+
101+
it.each(OTHER_PATHS)(
102+
'leaves %s without a debugger statement on a Windows path',
103+
testPath => {
104+
expect(transformTestFile(onWindows(testPath), 'run();')).toBe('run();');
105+
},
106+
);
107+
108+
it.each([
109+
`/home/__tests__/react-native/${GENERATED_ENTRYPOINT_PATH}`,
110+
`C:\\__tests__\\react-native\\${GENERATED_ENTRYPOINT_PATH.replaceAll('/', '\\')}`,
111+
])(
112+
'leaves the generated entrypoint %s of a checkout in a __tests__ folder without a debugger statement',
113+
filename => {
114+
expect(transformTestFile(filename, 'run();')).toBe('run();');
115+
},
116+
);
117+
118+
it.each([
119+
['Libraries/Components/View/__tests__/View-itest.js', 'View'],
120+
['my-library/__tests__/Example-itest.ts', 'Example'],
121+
['my-library/__tests__/Example-itest.tsx', 'Example'],
122+
[
123+
'Libraries/Components/View/__tests__/View-itest.fb.js',
124+
'View-itest.fb.js',
125+
],
126+
['my-library/__tests__/Example-itest.fb.tsx', 'Example-itest.fb.tsx'],
127+
])('names %s as %s in titles', (testPath, name) => {
128+
expect(getFantomTestName(`/repository/${testPath}`)).toBe(name);
129+
});
130+
});

‎private/react-native-fantom/config/babel-plugins/inject-debugger-statements-in-tests.js‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,33 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @noflow
7+
* @flow strict
88
* @format
99
*/
1010

11+
'use strict';
12+
13+
/*::
14+
import type {PluginObj} from '@babel/core';
15+
import typeof * as Types from '@babel/types';
16+
17+
type State = Readonly<{filename?: ?string, ...}>;
18+
*/
19+
20+
const {isFantomTestFile} = require('../fantomTestFiles');
21+
1122
/**
1223
* This transform injects a single `debugger;` statement at the top of every
1324
* Fantom test, so we can automatically stop on them when debugging.
1425
*/
15-
module.exports = function ({types: t}) {
26+
module.exports = function (
27+
{types: t} /*: {types: Types} */,
28+
) /*: PluginObj<State> */ {
1629
return {
1730
name: 'inject-debugger-statements-in-tests',
1831
visitor: {
1932
Program(path, state) {
20-
const filename = state.filename || '';
21-
if (
22-
(filename.endsWith('-itest.js') ||
23-
filename.endsWith('-itest.fb.js')) &&
24-
!filename.includes('/.out/')
25-
) {
33+
if (state.filename != null && isFantomTestFile(state.filename)) {
2634
// Check if the first statement is already a debugger statement
2735
const first = path.node.body[0];
2836
if (!first || first.type !== 'DebuggerStatement') {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow strict
8+
* @format
9+
*/
10+
11+
'use strict';
12+
13+
const path = require('node:path');
14+
15+
const FANTOM_TEST_FILE_EXTENSION = '\\.(js|tsx?)';
16+
17+
// Meta-internal tests add `.fb` before the extension.
18+
const FANTOM_TEST_REGEX = `/__tests__/.*-itest(\\.fb)?${FANTOM_TEST_FILE_EXTENSION}$`;
19+
20+
const FANTOM_TEST_PATTERN = new RegExp(FANTOM_TEST_REGEX);
21+
22+
// The titles of Meta-internal `-itest.fb.js` tests keep the whole file name.
23+
const FANTOM_TEST_NAME_SUFFIX = new RegExp(
24+
`-itest${FANTOM_TEST_FILE_EXTENSION}$`,
25+
);
26+
27+
function isFantomTestFile(filename /*: string */) /*: boolean */ {
28+
// Jest matches `testRegex` against a Windows path by rewriting its `/`.
29+
const normalizedFilename = filename.replaceAll('\\', '/');
30+
return (
31+
FANTOM_TEST_PATTERN.test(normalizedFilename) &&
32+
// The runner names each test's generated entrypoint in `.out` after it.
33+
!normalizedFilename.includes('/.out/')
34+
);
35+
}
36+
37+
function getFantomTestName(testPath /*: string */) /*: string */ {
38+
return path.basename(testPath).replace(FANTOM_TEST_NAME_SUFFIX, '');
39+
}
40+
41+
module.exports = {FANTOM_TEST_REGEX, getFantomTestName, isFantomTestFile};

‎private/react-native-fantom/config/jest.config.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
'use strict';
1212

1313
const baseConfig = require('../../../jest.config');
14+
const {FANTOM_TEST_REGEX} = require('./fantomTestFiles');
1415
const os = require('node:os');
1516
const path = require('node:path');
1617

@@ -49,8 +50,7 @@ module.exports = {
4950
'cpp',
5051
'h',
5152
] /*:: as ReadonlyArray<string> */,
52-
// This allows running Meta-internal tests with the `-test.fb.js` suffix.
53-
testRegex: '/__tests__/.*-itest(\\.fb)?\\.js$',
53+
testRegex: FANTOM_TEST_REGEX,
5454
testPathIgnorePatterns: baseConfig.testPathIgnorePatterns,
5555
transformIgnorePatterns: ['.*'],
5656
testRunner: '<rootDir>/private/react-native-fantom/runner/index.js',

‎private/react-native-fantom/config/metro-babel-transformer.flow.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ const transform: BabelTransformer['transform'] = (
2424
...args,
2525
plugins: [
2626
...(args.plugins ?? []),
27-
// $FlowExpectedError[untyped-import]
2827
require('./babel-plugins/inject-debugger-statements-in-tests'),
2928
...(args.options.customTransformOptions?.collectCoverage === 'true'
3029
? [
@@ -61,6 +60,7 @@ module.exports = {
6160
fs.readFileSync(
6261
require.resolve('./babel-plugins/inject-debugger-statements-in-tests'),
6362
),
63+
fs.readFileSync(require.resolve('./fantomTestFiles')),
6464
];
6565
cacheKeyParts.forEach(part => key.update(part));
6666
return key.digest('hex');

‎private/react-native-fantom/runner/runner.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import type {
2828
HermesVariant,
2929
} from './utils';
3030

31+
import {getFantomTestName} from '../config/fantomTestFiles';
3132
import {printBenchmarkResultsRanking} from './benchmarkUtils';
3233
import {createBundle, createSourceMap} from './bundling';
3334
import {shouldCollectCoverage} from './coverageUtils';
@@ -553,7 +554,7 @@ module.exports = async function runTest(
553554
const formattedFantomConfig = formatFantomConfig(testConfig);
554555
if (formattedFantomConfig) {
555556
result.ancestorTitles.unshift(
556-
`${path.basename(testPath, '-itest.js')} (${formatFantomConfig(testConfig)})`,
557+
`${getFantomTestName(testPath)} (${formattedFantomConfig})`,
557558
);
558559
}
559560
});
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @format
8+
*/
9+
10+
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
11+
12+
import * as Fantom from '@react-native/fantom';
13+
import * as React from 'react';
14+
import {Text} from 'react-native';
15+
16+
type GreetingProps = Readonly<{name: string}>;
17+
18+
function Greeting({name}: GreetingProps): React.ReactNode {
19+
return <Text nativeID="greeting">Hello, {name}</Text>;
20+
}
21+
22+
describe('a Fantom test written in TypeScript', () => {
23+
it('renders a component typed with TypeScript', () => {
24+
const root = Fantom.createRoot();
25+
const props = {name: 'Fantom'} satisfies GreetingProps;
26+
27+
Fantom.runTask(() => {
28+
root.render(<Greeting {...props} />);
29+
});
30+
31+
expect(root.getRenderedOutput({props: ['nativeID']}).toJSX()).toEqual(
32+
<rn-paragraph nativeID="greeting">Hello, Fantom</rn-paragraph>,
33+
);
34+
});
35+
});

0 commit comments

Comments
 (0)