forked from jestjs/jest
/
getCallsite.test.ts
77 lines (64 loc) 路 2.5 KB
/
getCallsite.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {originalPositionFor} from '@jridgewell/trace-mapping';
import * as fs from 'graceful-fs';
import getCallsite from '../getCallsite';
jest.mock('graceful-fs');
jest.mock('@jridgewell/trace-mapping', () => {
const actual = jest.requireActual('@jridgewell/trace-mapping');
return {
...actual,
originalPositionFor: jest.fn(actual.originalPositionFor),
};
});
describe('getCallsite', () => {
test('without source map', () => {
const site = getCallsite(0);
expect(site.getFileName()).toEqual(__filename);
expect(site.getColumnNumber()).toEqual(expect.any(Number));
expect(site.getLineNumber()).toEqual(expect.any(Number));
expect(fs.readFileSync).not.toHaveBeenCalled();
});
test('ignores errors when fs throws', () => {
(fs.readFileSync as jest.Mock).mockImplementation(() => {
throw new Error('Mock error');
});
const site = getCallsite(0, new Map([[__filename, 'mockedSourceMapFile']]));
expect(site.getFileName()).toEqual(__filename);
expect(site.getColumnNumber()).toEqual(expect.any(Number));
expect(site.getLineNumber()).toEqual(expect.any(Number));
expect(fs.readFileSync).toHaveBeenCalledWith('mockedSourceMapFile', 'utf8');
});
test('reads source map file to determine line and column', () => {
(fs.readFileSync as jest.Mock).mockImplementation(() =>
JSON.stringify({
file: 'file.js',
mappings: 'AAAA,OAAO,MAAM,KAAK,GAAG,QAAd',
names: [],
sources: ['file.js'],
sourcesContent: ["export const hello = 'foobar';\\n"],
version: 3,
}),
);
const sourceMapColumn = 1;
const sourceMapLine = 2;
jest.mocked(originalPositionFor).mockImplementation(() => ({
column: sourceMapColumn,
line: sourceMapLine,
}));
const site = getCallsite(0, new Map([[__filename, 'mockedSourceMapFile']]));
expect(site.getFileName()).toEqual(__filename);
expect(site.getColumnNumber()).toEqual(sourceMapColumn);
expect(site.getLineNumber()).toEqual(sourceMapLine);
expect(originalPositionFor).toHaveBeenCalledTimes(1);
expect(originalPositionFor).toHaveBeenCalledWith(expect.anything(), {
column: expect.any(Number),
line: expect.any(Number),
});
expect(fs.readFileSync).toHaveBeenCalledWith('mockedSourceMapFile', 'utf8');
});
});