|
| 1 | +import fs from 'fs' |
| 2 | +import {getUserCodeFrame} from '../get-user-code-frame' |
| 3 | + |
| 4 | +jest.mock('fs', () => ({ |
| 5 | + // We setup the contents of a sample file |
| 6 | + readFileSync: jest.fn( |
| 7 | + () => ` |
| 8 | + import {screen} from '@testing-library/dom' |
| 9 | + it('renders', () => { |
| 10 | + document.body.appendChild( |
| 11 | + document.createTextNode('Hello world') |
| 12 | + ) |
| 13 | + screen.debug() |
| 14 | + expect(screen.getByText('Hello world')).toBeInTheDocument() |
| 15 | + }) |
| 16 | + `, |
| 17 | + ), |
| 18 | +})) |
| 19 | + |
| 20 | +const userStackFrame = 'at somethingWrong (/sample-error/error-example.js:7:14)' |
| 21 | + |
| 22 | +let globalErrorMock |
| 23 | + |
| 24 | +beforeEach(() => { |
| 25 | + // Mock global.Error so we can setup our own stack messages |
| 26 | + globalErrorMock = jest.spyOn(global, 'Error') |
| 27 | +}) |
| 28 | + |
| 29 | +afterEach(() => { |
| 30 | + global.Error.mockRestore() |
| 31 | +}) |
| 32 | + |
| 33 | +test('it returns only user code frame when code frames from node_modules are first', () => { |
| 34 | + const stack = `Error: Kaboom |
| 35 | + at Object.<anonymous> (/sample-error/node_modules/@es2050/console/build/index.js:4:10) |
| 36 | + ${userStackFrame} |
| 37 | + ` |
| 38 | + globalErrorMock.mockImplementationOnce(() => ({stack})) |
| 39 | + const userTrace = getUserCodeFrame(stack) |
| 40 | + |
| 41 | + expect(userTrace).toMatchInlineSnapshot(` |
| 42 | + "/sample-error/error-example.js:7:14 |
| 43 | + 5 | document.createTextNode('Hello world') |
| 44 | + 6 | ) |
| 45 | + > 7 | screen.debug() |
| 46 | + | ^ |
| 47 | + " |
| 48 | + `) |
| 49 | +}) |
| 50 | + |
| 51 | +test('it returns only user code frame when node code frames are present afterwards', () => { |
| 52 | + const stack = `Error: Kaboom |
| 53 | + at Object.<anonymous> (/sample-error/node_modules/@es2050/console/build/index.js:4:10) |
| 54 | + ${userStackFrame} |
| 55 | + at Object.<anonymous> (/sample-error/error-example.js:14:1) |
| 56 | + at internal/main/run_main_module.js:17:47 |
| 57 | + ` |
| 58 | + globalErrorMock.mockImplementationOnce(() => ({stack})) |
| 59 | + const userTrace = getUserCodeFrame() |
| 60 | + |
| 61 | + expect(userTrace).toMatchInlineSnapshot(` |
| 62 | + "/sample-error/error-example.js:7:14 |
| 63 | + 5 | document.createTextNode('Hello world') |
| 64 | + 6 | ) |
| 65 | + > 7 | screen.debug() |
| 66 | + | ^ |
| 67 | + " |
| 68 | + `) |
| 69 | +}) |
| 70 | + |
| 71 | +test("it returns empty string if file from code frame can't be read", () => { |
| 72 | + // Make fire read purposely fail |
| 73 | + fs.readFileSync.mockImplementationOnce(() => { |
| 74 | + throw Error() |
| 75 | + }) |
| 76 | + const stack = `Error: Kaboom |
| 77 | + ${userStackFrame} |
| 78 | + ` |
| 79 | + globalErrorMock.mockImplementationOnce(() => ({stack})) |
| 80 | + |
| 81 | + expect(getUserCodeFrame(stack)).toEqual('') |
| 82 | +}) |
0 commit comments