|
| 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 | +const translateSourceFile = require('../../../translateSourceFile'); |
| 12 | +const replaceLegacyFunctionWithFunction = require('../replaceLegacyFunctionWithFunction'); |
| 13 | +const {parse, print} = require('flow-transform'); |
| 14 | + |
| 15 | +const prettierOptions = {parser: 'babel'}; |
| 16 | + |
| 17 | +async function translate(code: string): Promise<string> { |
| 18 | + const parsed = await parse(code); |
| 19 | + const result = await replaceLegacyFunctionWithFunction(parsed); |
| 20 | + return print(result.ast, result.mutatedCode, prettierOptions); |
| 21 | +} |
| 22 | + |
| 23 | +describe('replaceLegacyFunctionWithFunction', () => { |
| 24 | + test('replaces LegacyFunction in return annotations', async () => { |
| 25 | + expect(await translate('function foo(): LegacyFunction {}')).toBe( |
| 26 | + 'function foo(): Function {}\n', |
| 27 | + ); |
| 28 | + }); |
| 29 | + |
| 30 | + test('replaces LegacyFunction in nullable unions', async () => { |
| 31 | + expect( |
| 32 | + await translate('let foo: ?((value?: string) => any) | ?LegacyFunction;'), |
| 33 | + ).toBe('let foo: ?((value?: string) => any) | ?Function;\n'); |
| 34 | + }); |
| 35 | + |
| 36 | + test('replaces LegacyFunction in type aliases', async () => { |
| 37 | + expect(await translate('type Foo = LegacyFunction;')).toBe( |
| 38 | + 'type Foo = Function;\n', |
| 39 | + ); |
| 40 | + }); |
| 41 | + |
| 42 | + test('preserves unrelated and qualified types', async () => { |
| 43 | + const code = 'type Foo = Function | Other.LegacyFunction;'; |
| 44 | + expect(await translate(code)).toBe(code + '\n'); |
| 45 | + }); |
| 46 | + |
| 47 | + test('preserves Function in the generated TypeScript API', async () => { |
| 48 | + const source = `export type Callbacks = { |
| 49 | + onPress?: ?((value?: string) => any) | ?LegacyFunction, |
| 50 | + listener: LegacyFunction, |
| 51 | + }; |
| 52 | + export function forkEvent(event: ?LegacyFunction): LegacyFunction { |
| 53 | + return event; |
| 54 | + }`; |
| 55 | + const result = await translateSourceFile(source, __filename); |
| 56 | + const original = await translateSourceFile( |
| 57 | + source.replaceAll('LegacyFunction', 'Function'), |
| 58 | + __filename, |
| 59 | + ); |
| 60 | + expect(result).toEqual(original); |
| 61 | + }); |
| 62 | +}); |
0 commit comments