|
| 1 | +import fs from 'fs'; |
| 2 | +import SourceMap from 'source-map'; |
| 3 | +import getCallsite from '../get_callsite'; |
| 4 | + |
| 5 | +jest.mock('fs'); |
| 6 | + |
| 7 | +describe('getCallsite', () => { |
| 8 | + test('without source map', () => { |
| 9 | + const site = getCallsite(0); |
| 10 | + |
| 11 | + expect(site.getFileName()).toEqual(__filename); |
| 12 | + expect(site.getColumnNumber()).toEqual(expect.any(Number)); |
| 13 | + expect(site.getLineNumber()).toEqual(expect.any(Number)); |
| 14 | + expect(fs.readFileSync).not.toHaveBeenCalled(); |
| 15 | + }); |
| 16 | + |
| 17 | + test('ignores errors when fs throws', () => { |
| 18 | + fs.readFileSync.mockImplementation(() => { |
| 19 | + throw new Error('Mock error'); |
| 20 | + }); |
| 21 | + |
| 22 | + const site = getCallsite(0, {[__filename]: 'mockedSourceMapFile'}); |
| 23 | + |
| 24 | + expect(site.getFileName()).toEqual(__filename); |
| 25 | + expect(site.getColumnNumber()).toEqual(expect.any(Number)); |
| 26 | + expect(site.getLineNumber()).toEqual(expect.any(Number)); |
| 27 | + expect(fs.readFileSync).toHaveBeenCalledWith('mockedSourceMapFile', 'utf8'); |
| 28 | + }); |
| 29 | + |
| 30 | + test('reads source map file to determine line and column', () => { |
| 31 | + fs.readFileSync.mockImplementation(() => 'file data'); |
| 32 | + |
| 33 | + const sourceMapColumn = 1; |
| 34 | + const sourceMapLine = 2; |
| 35 | + SourceMap.SourceMapConsumer = class { |
| 36 | + originalPositionFor(params) { |
| 37 | + expect(params).toMatchObject({ |
| 38 | + column: expect.any(Number), |
| 39 | + line: expect.any(Number), |
| 40 | + }); |
| 41 | + |
| 42 | + return { |
| 43 | + column: sourceMapColumn, |
| 44 | + line: sourceMapLine, |
| 45 | + }; |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + const site = getCallsite(0, {[__filename]: 'mockedSourceMapFile'}); |
| 50 | + |
| 51 | + expect(site.getFileName()).toEqual(__filename); |
| 52 | + expect(site.getColumnNumber()).toEqual(sourceMapColumn); |
| 53 | + expect(site.getLineNumber()).toEqual(sourceMapLine); |
| 54 | + expect(fs.readFileSync).toHaveBeenCalledWith('mockedSourceMapFile', 'utf8'); |
| 55 | + }); |
| 56 | +}); |
0 commit comments