-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathmockNpm.test.ts
More file actions
364 lines (316 loc) · 12.2 KB
/
mockNpm.test.ts
File metadata and controls
364 lines (316 loc) · 12.2 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//
// The npm test fixture got complicated enough to need tests...
// But this added complexity greatly speeds up the other npm-related tests by removing the
// dependency on actual npm CLI calls and a fake registry (which are very slow).
//
import { afterAll, afterEach, beforeAll, describe, expect, it, jest } from '@jest/globals';
import fs from 'fs-extra';
import { NpmResult, npm } from '../packageManager/npm';
import { PackageJson } from '../types/PackageInfo';
import { initNpmMock, _makeRegistryData, _mockNpmPublish, _mockNpmShow } from './mockNpm';
jest.mock('fs-extra');
jest.mock('../packageManager/npm');
describe('_makeRegistryData', () => {
it('returns empty data', () => {
expect(_makeRegistryData({})).toEqual({});
});
it('uses provided dist-tags and versions, and fills in other data', () => {
const data = _makeRegistryData({
foo: {
versions: ['1.0.0', '1.0.1', '2.0.0-beta'],
'dist-tags': { latest: '1.0.1', beta: '2.0.0-beta' },
},
bar: {
versions: ['1.0.0'],
'dist-tags': { latest: '1.0.0' },
},
});
expect(data).toEqual({
foo: {
'dist-tags': { latest: '1.0.1', beta: '2.0.0-beta' },
versions: ['1.0.0', '1.0.1', '2.0.0-beta'],
versionData: {
'1.0.0': { name: 'foo', version: '1.0.0' },
'1.0.1': { name: 'foo', version: '1.0.1' },
'2.0.0-beta': { name: 'foo', version: '2.0.0-beta' },
},
},
bar: {
'dist-tags': { latest: '1.0.0' },
versions: ['1.0.0'],
versionData: {
'1.0.0': { name: 'bar', version: '1.0.0' },
},
},
});
});
it('fills in missing dist-tags from versions', () => {
const data = _makeRegistryData({
foo: { versions: ['1.0.0', '1.0.1'] },
});
expect(data.foo['dist-tags']).toEqual({ latest: '1.0.1' });
});
it('sorts versions when determining latest dist-tag', () => {
const data = _makeRegistryData({
foo: { versions: ['1.0.1', '2.0.0', '0.1.0'] },
});
expect(data.foo['dist-tags']).toEqual({ latest: '2.0.0' });
});
it('fills in missing latest dist-tag from versions', () => {
const data = _makeRegistryData({
foo: { versions: ['1.0.0', '1.0.1', '1.0.0-beta'], 'dist-tags': { beta: '1.0.0-beta' } },
});
expect(data.foo['dist-tags']).toEqual({ latest: '1.0.1', beta: '1.0.0-beta' });
});
it('fills in missing versions from dist-tags', () => {
const data = _makeRegistryData({
foo: { 'dist-tags': { beta: '2.0.0-beta', latest: '1.0.1' } },
});
expect(data.foo.versions).toEqual(['1.0.1', '2.0.0-beta']);
});
it('throws if a package provides neither versions nor dist-tags', () => {
expect(() => _makeRegistryData({ foo: {} })).toThrow(/must include either versions or dist-tags for foo/);
});
});
describe('_mockNpmShow', () => {
function getShowResult(
params: { error: string } | { data: ReturnType<typeof _makeRegistryData>; name: string; version: string }
) {
let output: string;
let isError: boolean;
if ('error' in params) {
output = params.error;
isError = true;
} else {
const { data, name, version } = params;
output = JSON.stringify({
// NOTE: this is sensitive to the order of keys used in _mockNpmShow
...data[name].versionData[version],
'dist-tags': data[name]['dist-tags'],
versions: data[name].versions,
});
isError = false;
}
return {
stdout: isError ? '' : output,
stderr: isError ? output : '',
all: output,
success: !isError,
failed: isError,
} as NpmResult;
}
const data = _makeRegistryData({
foo: {
versions: ['1.0.0-beta', '1.0.0', '1.0.1'],
'dist-tags': { latest: '1.0.1', beta: '1.0.0-beta' },
},
'@foo/bar': {
versions: ['2.0.0-beta', '2.0.0', '2.0.1'],
'dist-tags': { latest: '2.0.1', beta: '2.0.0-beta' },
},
});
it("errors if package doesn't exist", () => {
const emptyData = _makeRegistryData({});
const result = _mockNpmShow(emptyData, ['foo'], {});
expect(result).toEqual(getShowResult({ error: '[fake] code E404 - foo - not found' }));
});
it('returns requested version plus dist-tags and version list', () => {
const result = _mockNpmShow(data, ['foo@1.0.0'], {});
expect(result).toEqual(getShowResult({ data: data, name: 'foo', version: '1.0.0' }));
});
it('returns requested version of scoped package', () => {
const result = _mockNpmShow(data, ['@foo/bar@2.0.0'], {});
expect(result).toEqual(getShowResult({ data, name: '@foo/bar', version: '2.0.0' }));
});
it('returns requested tag', () => {
const result = _mockNpmShow(data, ['foo@beta'], {});
expect(result).toEqual(getShowResult({ data, name: 'foo', version: '1.0.0-beta' }));
});
it('returns requested tag of scoped package', () => {
const result = _mockNpmShow(data, ['@foo/bar@beta'], {});
expect(result).toEqual(getShowResult({ data, name: '@foo/bar', version: '2.0.0-beta' }));
});
it('returns latest version if no version requested', () => {
const result = _mockNpmShow(data, ['foo'], {});
expect(result).toEqual(getShowResult({ data, name: 'foo', version: '1.0.1' }));
});
it('returns latest version of scoped package if no version requested', () => {
const result = _mockNpmShow(data, ['@foo/bar'], {});
expect(result).toEqual(getShowResult({ data, name: '@foo/bar', version: '2.0.1' }));
});
it("errors if requested version doesn't exist", () => {
const result = _mockNpmShow(data, ['foo@2.0.0'], {});
expect(result).toEqual(getShowResult({ error: '[fake] code E404 - foo@2.0.0 - not found' }));
});
// support for this could be added later
it('currently throws if requested version is a range', () => {
expect(() => _mockNpmShow(data, ['foo@^1.0.0'], {})).toThrow(/not currently supported/);
});
});
describe('_mockNpmPublish', () => {
function getPublishResult(params: { error?: string; tag?: string }) {
const { error, tag } = params;
if (!error && !packageJson) throw new Error('packageJson not set');
const stdout = error ? '' : `[fake] published ${packageJson?.name}@${packageJson?.version} with tag ${tag}`;
return {
stdout,
stderr: error || '',
all: stdout || error,
success: !error,
failed: !!error,
} as NpmResult;
}
let packageJson: PackageJson | undefined;
beforeAll(() => {
(fs.readJsonSync as jest.MockedFunction<typeof fs.readJsonSync>).mockImplementation(() => {
if (!packageJson) throw new Error('packageJson not set');
return packageJson;
});
});
afterEach(() => {
packageJson = undefined;
});
afterAll(() => {
jest.restoreAllMocks();
});
it('throws if cwd is not specified', () => {
expect(() => _mockNpmPublish({}, [], {})).toThrow('cwd is required for mock npm publish');
});
it('errors if reading package.json fails', () => {
// this error is from the fs.readJsonSync mock, but it's the same code path as if reading the file fails
expect(() => _mockNpmPublish({}, [], { cwd: 'fake' })).toThrow('packageJson not set');
});
it('errors on re-publish', () => {
const data = _makeRegistryData({ foo: { versions: ['1.0.0'] } });
packageJson = { name: 'foo', version: '1.0.0', main: 'nope.js' };
const result = _mockNpmPublish(data, [], { cwd: 'fake' });
expect(result).toEqual(
getPublishResult({
error: '[fake] EPUBLISHCONFLICT foo@1.0.0 already exists in registry',
})
);
// verify that the package didn't get updated in the fake registry
// (the "main" field specified above won't exist on the default version)
expect(data.foo.versionData['1.0.0'].main).toBeUndefined();
});
it('publishes to empty registry with default tag latest', () => {
const data = _makeRegistryData({});
packageJson = { name: 'foo', version: '1.0.0', main: 'index.js' };
const result = _mockNpmPublish(data, [], { cwd: 'fake' });
expect(result).toEqual(getPublishResult({ tag: 'latest' }));
expect(data.foo).toEqual({
versions: ['1.0.0'],
'dist-tags': { latest: '1.0.0' },
versionData: { '1.0.0': packageJson },
});
});
it('publishes package and updates latest tag', () => {
const data = _makeRegistryData({
foo: { versions: ['1.0.0'], 'dist-tags': { latest: '1.0.0' } },
});
packageJson = { name: 'foo', version: '2.0.0', main: 'index.js' };
const result = _mockNpmPublish(data, [], { cwd: 'fake' });
expect(result).toEqual(getPublishResult({ tag: 'latest' }));
expect(data.foo).toEqual({
versions: ['1.0.0', '2.0.0'],
// latest tag is updated
'dist-tags': { latest: '2.0.0' },
versionData: {
'1.0.0': { name: 'foo', version: '1.0.0' },
'2.0.0': packageJson,
},
});
});
it('publishes requested tag and does not update latest', () => {
const data = _makeRegistryData({
foo: { versions: ['1.0.0'], 'dist-tags': { latest: '1.0.0', beta: '1.0.0' } },
});
packageJson = { name: 'foo', version: '2.0.0', main: 'index.js' };
const result = _mockNpmPublish(data, ['--tag', 'beta'], { cwd: 'fake' });
expect(result).toEqual(getPublishResult({ tag: 'beta' }));
expect(data.foo).toEqual({
versions: ['1.0.0', '2.0.0'],
// beta tag updated, latest not updated
'dist-tags': { beta: '2.0.0', latest: '1.0.0' },
versionData: {
'1.0.0': { name: 'foo', version: '1.0.0' },
'2.0.0': packageJson,
},
});
});
it('does a dry run', () => {
const data = _makeRegistryData({});
packageJson = { name: 'foo', version: '1.0.0', main: 'index.js' };
const result = _mockNpmPublish(data, ['--dry-run'], { cwd: 'fake' });
// logs like it published
expect(result).toEqual(getPublishResult({ tag: 'latest' }));
// doesn't actually publish
expect(data).toEqual({});
});
});
describe('mockNpm', () => {
const npmMock = initNpmMock();
let packageJson: PackageJson | undefined;
beforeAll(() => {
(fs.readJsonSync as jest.MockedFunction<typeof fs.readJsonSync>).mockImplementation(() => {
if (!packageJson) throw new Error('packageJson not set');
return packageJson;
});
});
afterEach(() => {
packageJson = undefined;
});
afterAll(() => {
jest.restoreAllMocks();
});
it('mocks npm show', async () => {
npmMock.setRegistryData({ foo: { versions: ['1.0.0'] } });
const result = await npm(['show', 'foo']);
expect(result).toMatchObject({
success: true,
stdout: expect.stringContaining('"name":"foo"'),
});
});
it('resets calls and registry after each test', async () => {
expect(npmMock.mock).not.toHaveBeenCalled();
// registry data for foo was set in the previous test but should have been cleared
const result = await npm(['show', 'foo']);
expect(result).toMatchObject({
success: false,
stderr: expect.stringContaining('not found'),
});
});
it('can "publish" a package to registry with helper', async () => {
npmMock.publishPackage({ name: 'foo', version: '1.0.0' });
const result = await npm(['show', 'foo']);
expect(result).toMatchObject({
success: true,
stdout: expect.stringContaining('"name":"foo"'),
});
});
it('mocks npm publish', async () => {
packageJson = { name: 'foo', version: '1.0.0' };
const result = await npm(['publish'], { cwd: 'fake' });
expect(result).toMatchObject({
success: true,
stdout: expect.stringContaining('published foo'),
});
});
it('throws on unsupported command', async () => {
await expect(() => npm(['pack'])).rejects.toThrow('Command not supported by mock npm: pack');
});
it('respects mocked command', async () => {
const mockShow = jest.fn(() => 'hi');
npmMock.setCommandOverride('show', mockShow as any);
const result = await npm(['show', 'foo']);
expect(result).toEqual('hi');
expect(mockShow).toHaveBeenCalledWith(expect.any(Object), ['foo'], undefined);
});
it("respects extra mocked command that's not normally supported", async () => {
const mockPack = jest.fn(() => 'hi');
npmMock.setCommandOverride('pack', mockPack as any);
const result = await npm(['pack']);
expect(result).toEqual('hi');
expect(mockPack).toHaveBeenCalledWith(expect.any(Object), [], undefined);
});
});