-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
280 lines (234 loc) · 7.29 KB
/
test.js
File metadata and controls
280 lines (234 loc) · 7.29 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
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const NextJSModuleIntegrityPlugin = require("./nextjs-module-integrity-plugin");
// Mock fs and crypto
jest.mock("fs");
jest.mock("crypto");
describe("NextJSModuleIntegrityPlugin", () => {
let plugin;
let mockCompiler;
let mockCompilation;
let mockCreateHash;
let mockDigest;
let mockCallback;
beforeEach(() => {
// Reset all mocks
jest.clearAllMocks();
// Setup crypto mocks
mockDigest = jest.fn().mockReturnValue("mocked-hash-value");
mockCreateHash = jest.fn().mockReturnValue({
update: jest.fn().mockReturnThis(),
digest: mockDigest,
});
crypto.createHash.mockImplementation(mockCreateHash);
// Setup fs mocks
fs.existsSync = jest.fn().mockReturnValue(false);
fs.writeFileSync = jest.fn();
fs.readFileSync = jest.fn().mockReturnValue("{}");
// Setup webpack compiler mocks
mockCallback = jest.fn();
mockCompilation = {
assets: {
"chunk1.js": {
source: () => 'const module1 = "content";',
size: () => 25,
},
"chunk2.js": {
source: () => 'const module2 = "content";',
size: () => 25,
},
"node_modules/test-package/index.js": {
source: () => "export default {}",
size: () => 15,
},
},
chunks: [
{
name: "chunk1",
getModules: jest
.fn()
.mockReturnValue([
{ resource: "/path/to/node_modules/test-package/index.js" },
]),
},
{
name: "chunk2",
getModules: jest
.fn()
.mockReturnValue([{ resource: "/path/to/src/local-module.js" }]),
},
],
};
mockCompiler = {
hooks: {
emit: { tapAsync: jest.fn() },
afterEmit: { tapAsync: jest.fn() },
},
};
// Create the plugin instance with default config
plugin = new NextJSModuleIntegrityPlugin();
});
test("initializes with default config", () => {
expect(plugin.config).toEqual({
packages: [],
algorithm: "sha384",
generateVercelConfig: true,
importMapPath: "importmap.json",
injectImportMap: true,
});
expect(plugin.importMap).toEqual({
imports: {},
integrity: {},
});
});
test("initializes with custom config", () => {
const customConfig = {
packages: ["react", "lodash"],
algorithm: "sha256",
generateVercelConfig: false,
importMapPath: "custom/path.json",
injectImportMap: false,
};
const customPlugin = new NextJSModuleIntegrityPlugin(customConfig);
expect(customPlugin.config).toEqual(customConfig);
});
test("apply method registers emit and afterEmit hooks", () => {
plugin.apply(mockCompiler);
expect(mockCompiler.hooks.emit.tapAsync).toHaveBeenCalledWith(
"NextJSModuleIntegrityPlugin",
expect.any(Function),
);
expect(mockCompiler.hooks.afterEmit.tapAsync).toHaveBeenCalledWith(
"NextJSModuleIntegrityPlugin",
expect.any(Function),
);
});
test("calculateIntegrity generates correct hash format", () => {
const content = "test content";
const result = plugin.calculateIntegrity(content);
expect(crypto.createHash).toHaveBeenCalledWith("sha384");
expect(mockDigest).toHaveBeenCalledWith("base64");
expect(result).toBe("sha384-mocked-hash-value");
});
test("addToImportMap adds entries correctly", () => {
plugin.addToImportMap("scripts/bundle.js", "sha384-hashvalue");
expect(plugin.importMap).toEqual({
imports: {
bundle: "/scripts/bundle.js",
},
integrity: {
"/scripts/bundle.js": "sha384-hashvalue",
},
});
});
test("chunkContainsPackage detects package in chunk", () => {
const containsPackage = plugin.chunkContainsPackage(
mockCompilation,
"chunk1",
"test-package",
);
expect(containsPackage).toBe(true);
});
test("chunkContainsPackage returns false when package not in chunk", () => {
const containsPackage = plugin.chunkContainsPackage(
mockCompilation,
"chunk2",
"test-package",
);
expect(containsPackage).toBe(false);
});
test("chunkContainsPackage returns false when chunk not found", () => {
const containsPackage = plugin.chunkContainsPackage(
mockCompilation,
"non-existent-chunk",
"test-package",
);
expect(containsPackage).toBe(false);
});
test("generateVercelConfig creates new config when file does not exist", () => {
// Setup plugin with some integrity hashes
plugin.importMap.integrity = {
"/bundle1.js": "sha384-hash1",
"/bundle2.js": "sha384-hash2",
};
plugin.generateVercelConfig();
expect(fs.existsSync).toHaveBeenCalledWith(
expect.stringContaining("vercel.json"),
);
expect(fs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining("vercel.json"),
expect.stringContaining('"Content-Security-Policy"'),
);
// Check the written content includes the integrity hashes
const writtenContent = fs.writeFileSync.mock.calls[0][1];
expect(writtenContent).toContain("sha384-hash1");
expect(writtenContent).toContain("sha384-hash2");
});
test("generateVercelConfig updates existing config when file exists", () => {
// Mock existing vercel.json
fs.existsSync.mockReturnValue(true);
fs.readFileSync.mockReturnValue(
JSON.stringify({
headers: [
{
source: "/(.*)",
headers: [
{
key: "Content-Security-Policy",
value: "default-src 'self'; script-src 'self'",
},
],
},
],
}),
);
// Setup plugin with some integrity hashes
plugin.importMap.integrity = {
"/bundle1.js": "sha384-hash1",
};
plugin.generateVercelConfig();
expect(fs.writeFileSync).toHaveBeenCalled();
const writtenContent = fs.writeFileSync.mock.calls[0][1];
// Verify the existing CSP was updated
expect(writtenContent).toContain("script-src 'self' 'sha384-hash1'");
});
test("emit hook processes assets and creates import map", () => {
// Get the emit hook function
plugin.apply(mockCompiler);
const emitFn = mockCompiler.hooks.emit.tapAsync.mock.calls[0][1];
// Call the emit hook function
emitFn(mockCompilation, mockCallback);
// Check that importmap.json was added to the assets
expect(mockCompilation.assets["importmap.json"]).toBeDefined();
expect(mockCallback).toHaveBeenCalled();
});
test("afterEmit hook generates Vercel config when enabled", () => {
// Spy on generateVercelConfig
const generateVercelConfigSpy = jest.spyOn(plugin, "generateVercelConfig");
// Get the afterEmit hook function
plugin.apply(mockCompiler);
const afterEmitFn = mockCompiler.hooks.afterEmit.tapAsync.mock.calls[0][1];
// Call the afterEmit hook function
afterEmitFn(mockCompilation, mockCallback);
// Check that generateVercelConfig was called
expect(generateVercelConfigSpy).toHaveBeenCalled();
expect(mockCallback).toHaveBeenCalled();
});
test("afterEmit hook does not generate Vercel config when disabled", () => {
// Create plugin with generateVercelConfig disabled
plugin = new NextJSModuleIntegrityPlugin({
generateVercelConfig: false,
});
// Spy on generateVercelConfig
const generateVercelConfigSpy = jest.spyOn(plugin, "generateVercelConfig");
// Get the afterEmit hook function
plugin.apply(mockCompiler);
const afterEmitFn = mockCompiler.hooks.afterEmit.tapAsync.mock.calls[0][1];
// Call the afterEmit hook function
afterEmitFn(mockCompilation, mockCallback);
// Check that generateVercelConfig was not called
expect(generateVercelConfigSpy).not.toHaveBeenCalled();
expect(mockCallback).toHaveBeenCalled();
});
});