main
js 102 lines 2.62 KB
Raw
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
8 'use strict';
9
10 const {tests} = require('./eslint-plugin-react-hooks-test-cases');
11 const {
12 runBabelPluginReactCompiler,
13 } = require('../dist/Babel/RunReactCompilerBabelPlugin');
14 const fs = require('fs');
15 const path = require('path');
16 const prettier = require('prettier');
17 const prettierConfigPath = require.resolve('../.prettierrc');
18 const process = require('process');
19 const {createHash} = require('crypto');
20 const {create} = require('domain');
21
22 const FIXTURES_DIR = path.join(
23 process.cwd(),
24 'src',
25 '__tests__',
26 'fixtures',
27 'compiler',
28 'rules-of-hooks'
29 );
30
31 const PRETTIER_OPTIONS = prettier.resolveConfig.sync(FIXTURES_DIR, {
32 config: prettierConfigPath,
33 });
34
35 const fixtures = [];
36 for (const test of tests.valid) {
37 fixtures.push({code: test.code, valid: true});
38 }
39 for (const test of tests.invalid) {
40 fixtures.push({code: test.code, valid: false});
41 }
42
43 for (const fixture of fixtures) {
44 let error = null;
45 let passes = true;
46 try {
47 // Does the fixture pass with hooks validation disabled? if not skip it
48 runBabelPluginReactCompiler(
49 fixture.code,
50 'rules-of-hooks.js',
51 'typescript',
52 {
53 environment: {
54 validateHooksUsage: false,
55 },
56 }
57 );
58 // Does the fixture pass with hooks validation enabled?
59 try {
60 runBabelPluginReactCompiler(
61 fixture.code,
62 'rules-of-hooks.js',
63 'typescript',
64 {
65 environment: {
66 validateHooksUsage: true,
67 },
68 }
69 );
70 } catch (e) {
71 passes = false;
72 }
73 } catch (e) {
74 error = e;
75 }
76 let code = fixture.code;
77 let prefix = '';
78 if (error !== null) {
79 prefix = `todo.bail.`;
80 code = `// @skip\n// Unsupported input\n${code}`;
81 } else if (fixture.valid === false) {
82 if (passes) {
83 prefix = `todo.error.invalid-`;
84 code = `// @skip\n// Passed but should have failed\n${code}`;
85 } else {
86 prefix = `error.invalid-`;
87 code = `// Expected to fail\n${code}`;
88 }
89 } else if (!passes) {
90 // oops, error when it should have passed
91 prefix = `todo.`;
92 code = `// @skip\n// Failed but should have passed\n${code}`;
93 }
94 const formatted = prettier.format(code, PRETTIER_OPTIONS);
95 const hmac = createHash('sha256');
96 hmac.update(formatted, 'utf8');
97 let name = `${prefix}rules-of-hooks-${hmac
98 .digest('hex')
99 .substring(0, 12)}.js`;
100 const fixturePath = path.join(FIXTURES_DIR, name);
101 fs.writeFileSync(fixturePath, formatted, 'utf8');
102 }