| 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 | import * as t from '@babel/types'; |
| 9 | import invariant from 'invariant'; |
| 10 | import {runBabelPluginReactCompiler} from '../Babel/RunReactCompilerBabelPlugin'; |
| 11 | import type {Logger, LoggerEvent} from '../Entrypoint'; |
| 12 | |
| 13 | it('logs successful compilation', () => { |
| 14 | const logs: [string | null, LoggerEvent][] = []; |
| 15 | const logger: Logger = { |
| 16 | logEvent(filename, event) { |
| 17 | logs.push([filename, event]); |
| 18 | }, |
| 19 | }; |
| 20 | |
| 21 | const _ = runBabelPluginReactCompiler( |
| 22 | 'function Component(props) { return <div>{props}</div> }', |
| 23 | 'test.js', |
| 24 | 'flow', |
| 25 | {logger, panicThreshold: 'all_errors'}, |
| 26 | ); |
| 27 | |
| 28 | const [filename, event] = logs.at(0)!; |
| 29 | expect(filename).toContain('test.js'); |
| 30 | expect(event.kind).toEqual('CompileSuccess'); |
| 31 | invariant(event.kind === 'CompileSuccess', 'typescript be smarter'); |
| 32 | expect(event.fnName).toEqual('Component'); |
| 33 | expect(event.fnLoc?.end).toEqual({column: 55, index: 55, line: 1}); |
| 34 | expect(event.fnLoc?.start).toEqual({column: 0, index: 0, line: 1}); |
| 35 | }); |
| 36 | |
| 37 | it('logs failed compilation', () => { |
| 38 | const logs: [string | null, LoggerEvent][] = []; |
| 39 | const logger: Logger = { |
| 40 | logEvent(filename, event) { |
| 41 | logs.push([filename, event]); |
| 42 | }, |
| 43 | }; |
| 44 | |
| 45 | expect(() => { |
| 46 | runBabelPluginReactCompiler( |
| 47 | 'function Component(props) { props.foo = 1; return <div>{props}</div> }', |
| 48 | 'test.js', |
| 49 | 'flow', |
| 50 | {logger, panicThreshold: 'all_errors'}, |
| 51 | ); |
| 52 | }).toThrow(); |
| 53 | |
| 54 | const [filename, event] = logs.at(0)!; |
| 55 | expect(filename).toContain('test.js'); |
| 56 | expect(event.kind).toEqual('CompileError'); |
| 57 | invariant(event.kind === 'CompileError', 'typescript be smarter'); |
| 58 | |
| 59 | expect(event.detail.severity).toEqual('Error'); |
| 60 | const errorDetail = event.detail.details?.find(d => d.kind === 'error'); |
| 61 | expect(errorDetail).toBeDefined(); |
| 62 | const loc = errorDetail!.loc as t.SourceLocation; |
| 63 | expect(loc.start).toEqual({column: 28, index: 28, line: 1}); |
| 64 | expect(loc.end).toEqual({column: 33, index: 33, line: 1}); |
| 65 | expect(loc.identifierName).toEqual('props'); |
| 66 | |
| 67 | // Make sure event.fnLoc is different from event.detail.loc |
| 68 | expect(event.fnLoc?.start).toEqual({column: 0, index: 0, line: 1}); |
| 69 | expect(event.fnLoc?.end).toEqual({column: 70, index: 70, line: 1}); |
| 70 | }); |