forked from JS-DevTools/npm-publish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnpm.js
81 lines (72 loc) · 1.87 KB
/
npm.js
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
"use strict";
const fs = require("fs");
const paths = require("./paths");
const { expect } = require("chai");
module.exports = {
/**
* Adds a stub behavior for our mock NPM binary
*/
mock ({ args, cwd, env, stdout, stderr, exitCode }) {
args = args || [];
cwd = cwd || paths.workspace;
env = env || {};
stdout = stdout || "";
stderr = stderr || "";
exitCode = exitCode || 0;
let mocks = readMocks();
let stub = { args, cwd, env, stdout, stderr, exitCode };
mocks.push(stub);
fs.writeFileSync(paths.mocks, JSON.stringify(mocks));
},
/**
* Returns the next stub behavior for the mock NPM binary
*
* @returns {{ args: string[], cwd: string, env: object, stdout: string, stderr: string, exitCode: number }}
*/
stub () {
let mocks = readMocks();
let stub = mocks.find((mock) => !mock.ran);
stub.ran = true;
fs.writeFileSync(paths.mocks, JSON.stringify(mocks));
return stub;
},
assert: {
/**
* Asserts that NPM did not run
*/
didNotRun () {
let mocks = readMocks();
expect(mocks).to.have.lengthOf(0, "NPM ran when it shouldn't have");
},
/**
* Asserts that all mocks ran the specified number of times
*/
ran (times) {
let mocks = readMocks();
for (let [index, stub] of mocks.entries()) {
if (!stub.ran) {
throw new Error(
`NPM call #${index + 1} did not run:\n` +
`EXPECTED: npm ${stub.args.join(" ")}\n` +
"ACTUAL: <not called>\n"
);
}
}
expect(mocks).to.have.lengthOf(times, `Expected NPM to be run ${times} times`);
},
},
};
/**
* Returns the contents of the NPM mock config file
*
* @returns {object[]}
*/
function readMocks () {
try {
let json = fs.readFileSync(paths.mocks, "utf8");
return JSON.parse(json);
}
catch (_) {
return [];
}
}