-
Notifications
You must be signed in to change notification settings - Fork 706
Expand file tree
/
Copy pathSassProcessor.test.ts
More file actions
848 lines (742 loc) · 38.7 KB
/
Copy pathSassProcessor.test.ts
File metadata and controls
848 lines (742 loc) · 38.7 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import path from 'node:path';
import nodeJsPath from 'node:path';
import { FileSystem, Path, Text } from '@rushstack/node-core-library';
import { MockScopedLogger } from '@rushstack/heft/lib/pluginFramework/logging/MockScopedLogger';
import { StringBufferTerminalProvider, Terminal } from '@rushstack/terminal';
import { type ICssOutputFolder, type ISassProcessorOptions, SassProcessor } from '../SassProcessor';
const projectFolder: string = path.resolve(__dirname, '../..');
const fixturesFolder: string = path.resolve(__dirname, '../../src/test/fixtures');
// Fake output folder paths - never actually written to disk because FileSystem.writeFileAsync is mocked.
const FAKE_OUTPUT_BASE_FOLDER: string = '/fake/output';
const NORMALIZED_PLATFORM_FAKE_OUTPUT_BASE_FOLDER: string = Path.convertToSlashes(
nodeJsPath.resolve(FAKE_OUTPUT_BASE_FOLDER)
);
const CSS_OUTPUT_FOLDER: string = `${FAKE_OUTPUT_BASE_FOLDER}/css`;
const DTS_OUTPUT_FOLDER: string = `${FAKE_OUTPUT_BASE_FOLDER}/dts`;
type ICreateProcessorOptions = Partial<
Pick<
ISassProcessorOptions,
| 'cssOutputFolders'
| 'doNotTrimOriginalFileExtension'
| 'dtsOutputFolders'
| 'exportAsDefault'
| 'fileExtensions'
| 'ignoreDeprecationsInDependencies'
| 'nonModuleFileExtensions'
| 'postProcessCssAsync'
| 'preserveIcssExports'
| 'silenceDeprecations'
| 'sourceMap'
| 'srcFolder'
>
>;
function createProcessor(
terminalProvider: StringBufferTerminalProvider,
options: ICreateProcessorOptions = {}
): {
processor: SassProcessor;
logger: MockScopedLogger;
} {
const terminal: Terminal = new Terminal(terminalProvider);
const logger: MockScopedLogger = new MockScopedLogger(terminal);
const processor: SassProcessor = new SassProcessor({
logger,
buildFolder: projectFolder,
concurrency: 1,
srcFolder: fixturesFolder,
dtsOutputFolders: [DTS_OUTPUT_FOLDER],
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: undefined }],
exportAsDefault: true,
...options
});
return { processor, logger };
}
async function compileFixtureAsync(processor: SassProcessor, fixtureFilename: string): Promise<void> {
await processor.compileFilesAsync(new Set([`${fixturesFolder}/${fixtureFilename}`]));
}
/**
* Replaces OS-/checkout-dependent fields in a source map JSON string with stable placeholders so
* the test can snapshot the result on any machine. Specifically, rewrites `sources[]` entries that
* point at the fixtures folder to a `fixtures/<name>` form, and normalizes `sourcesContent[]`
* line endings to LF.
*/
function normalizeSourceMapForSnapshot(json: string): string {
const map: {
sources?: string[];
sourcesContent?: string[];
[key: string]: unknown;
} = JSON.parse(json);
if (map.sources) {
// sources[] are relative paths from the .css.map output file back to the source .scss.
// In real use both ends live on disk in the same project so this is stable; in this test
// the output folder is the mocked /fake/output/css/ while the source is the real fixture
// on disk, so the relative path traverses the entire checkout-specific path from /fake up
// to the real fixtures folder. Strip everything before the "/fixtures/" segment so the
// snapshot is checkout-independent.
map.sources = map.sources.map((source) => {
const normalized: string = Path.convertToSlashes(source);
const fixturesIndex: number = normalized.indexOf('/fixtures/');
if (fixturesIndex >= 0) {
return normalized.slice(fixturesIndex + 1);
}
const lastSlash: number = normalized.lastIndexOf('/');
return `fixtures/${lastSlash >= 0 ? normalized.slice(lastSlash + 1) : normalized}`;
});
}
if (map.sourcesContent) {
map.sourcesContent = map.sourcesContent.map(Text.convertToLf);
}
return JSON.stringify(map);
}
describe(SassProcessor.name, () => {
let terminalProvider: StringBufferTerminalProvider;
/** Files captured by the mocked FileSystem.writeFileAsync, keyed by absolute path. */
let writtenFiles: Map<string, string>;
/** Returns the content written to a path whose last segment matches the given filename. */
function getWrittenFile(filename: string): string {
for (const [filePath, content] of writtenFiles) {
if (filePath.endsWith(`/${filename}`)) {
return content;
}
}
throw new Error(
`No file written matching ".../${filename}". Written paths:\n${[...writtenFiles.keys()].join('\n')}`
);
}
/** Returns all paths written that end with the given suffix. */
function getAllWrittenPathsMatching(suffix: string): string[] {
return [...writtenFiles.keys()].filter((p) => p.endsWith(suffix));
}
function getCssOutput(fixtureFilename: string): string {
// SassProcessor strips the last extension then appends .css
// export-only.module.scss → export-only.module.css
const withoutExt: string = fixtureFilename.slice(0, fixtureFilename.lastIndexOf('.'));
return getWrittenFile(`${withoutExt}.css`);
}
function getDtsOutput(fixtureFilename: string): string {
return getWrittenFile(`${fixtureFilename}.d.ts`);
}
function getJsShimOutput(fixtureFilename: string): string {
return getWrittenFile(`${fixtureFilename}.js`);
}
beforeEach(() => {
terminalProvider = new StringBufferTerminalProvider();
writtenFiles = new Map();
jest.spyOn(FileSystem, 'writeFileAsync').mockImplementation(async (filePath, content) => {
filePath = Path.convertToSlashes(filePath).replace(
NORMALIZED_PLATFORM_FAKE_OUTPUT_BASE_FOLDER,
FAKE_OUTPUT_BASE_FOLDER
);
let serialized: string = String(content);
// Source map contents include the absolute-relative path back to the source file and the
// verbatim source file bytes. Both vary by checkout location and OS line endings, which makes
// raw snapshots non-portable. Normalize them to stable forms before storing.
if (filePath.endsWith('.css.map')) {
serialized = normalizeSourceMapForSnapshot(serialized);
}
writtenFiles.set(filePath, serialized);
});
});
afterEach(() => {
jest.restoreAllMocks();
expect(writtenFiles).toMatchSnapshot('written-files');
expect(terminalProvider.getAllOutputAsChunks({ asLines: true })).toMatchSnapshot('terminal-output');
});
describe('export-only.module.scss', () => {
it('strips the :export block from CSS when preserveIcssExports is false', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'export-only.module.scss');
const css: string = getCssOutput('export-only.module.scss');
expect(css).not.toContain(':export');
});
it('preserves the :export block in CSS when preserveIcssExports is true', async () => {
const { processor } = createProcessor(terminalProvider, { preserveIcssExports: true });
await compileFixtureAsync(processor, 'export-only.module.scss');
const css: string = getCssOutput('export-only.module.scss');
expect(css).toContain(':export');
});
it('generates the same .d.ts regardless of preserveIcssExports', async () => {
const { processor: processorFalse } = createProcessor(terminalProvider);
await compileFixtureAsync(processorFalse, 'export-only.module.scss');
const dtsFalse: string = getDtsOutput('export-only.module.scss');
writtenFiles.clear();
const { processor: processorTrue } = createProcessor(terminalProvider, {
preserveIcssExports: true
});
await compileFixtureAsync(processorTrue, 'export-only.module.scss');
const dtsTrue: string = getDtsOutput('export-only.module.scss');
expect(dtsFalse).toEqual(dtsTrue);
});
});
describe('classes-and-exports.module.scss', () => {
it('strips the :export block from CSS when preserveIcssExports is false', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const css: string = getCssOutput('classes-and-exports.module.scss');
expect(css).not.toContain(':export');
expect(css).toContain('.root');
});
it('preserves the :export block in CSS when preserveIcssExports is true', async () => {
const { processor } = createProcessor(terminalProvider, { preserveIcssExports: true });
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const css: string = getCssOutput('classes-and-exports.module.scss');
expect(css).toContain(':export');
expect(css).toContain('.root');
});
it('generates correct .d.ts with both class names and :export values', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const dts: string = getDtsOutput('classes-and-exports.module.scss');
expect(dts).toContain('root');
expect(dts).toContain('highlighted');
expect(dts).toContain('themeColor');
expect(dts).toContain('spacing');
});
it('generates named exports in .d.ts when exportAsDefault is false', async () => {
// cssOutputFolders requires exportAsDefault: true, so omit it here
const { processor } = createProcessor(terminalProvider, {
exportAsDefault: false,
cssOutputFolders: []
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const dts: string = getDtsOutput('classes-and-exports.module.scss');
// Named exports: "export const root: string;" instead of a default interface
expect(dts).toContain('export const root');
expect(dts).toContain('export const highlighted');
expect(dts).toContain('export const themeColor');
expect(dts).not.toContain('export default');
});
});
describe('sass-variables-and-exports.module.scss (Sass variables, nesting, BEM)', () => {
it('resolves Sass variables and expands nested rules in CSS output', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'sass-variables-and-exports.module.scss');
const css: string = getCssOutput('sass-variables-and-exports.module.scss');
// Sass variables should be resolved to literal values
expect(css).toContain('#0078d4');
expect(css).toContain('#106ebe');
// Nested rules should be expanded
expect(css).toContain('.container:hover');
expect(css).toContain('.container__title');
// :export block should be stripped (preserveIcssExports: false)
expect(css).not.toContain(':export');
});
it('resolves Sass variables inside the :export block when preserveIcssExports is true', async () => {
const { processor } = createProcessor(terminalProvider, { preserveIcssExports: true });
await compileFixtureAsync(processor, 'sass-variables-and-exports.module.scss');
const css: string = getCssOutput('sass-variables-and-exports.module.scss');
// The :export block should contain resolved values, not Sass variable names
expect(css).toContain(':export');
expect(css).toContain('#0078d4');
expect(css).not.toContain('$primary-color');
});
it('generates .d.ts with resolved :export keys as typed properties', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'sass-variables-and-exports.module.scss');
const dts: string = getDtsOutput('sass-variables-and-exports.module.scss');
expect(dts).toContain('container');
expect(dts).toContain('primaryColor');
expect(dts).toContain('secondaryColor');
expect(dts).toContain('baseSpacing');
});
});
describe('mixin-with-exports.module.scss (Sass @mixin)', () => {
it('expands @mixin calls in CSS output', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'mixin-with-exports.module.scss');
const css: string = getCssOutput('mixin-with-exports.module.scss');
// Mixin output should be inlined - no @mixin or @include in the output
expect(css).not.toContain('@mixin');
expect(css).not.toContain('@include');
expect(css).toContain('display: flex');
expect(css).toContain('.card');
expect(css).toContain('.card--vertical');
});
it('preserves :export alongside expanded @mixin output when preserveIcssExports is true', async () => {
const { processor } = createProcessor(terminalProvider, { preserveIcssExports: true });
await compileFixtureAsync(processor, 'mixin-with-exports.module.scss');
const css: string = getCssOutput('mixin-with-exports.module.scss');
expect(css).toContain(':export');
expect(css).toContain('display: flex');
expect(css).not.toContain('@mixin');
});
it('generates .d.ts with :export values and class names from @mixin-using file', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'mixin-with-exports.module.scss');
const dts: string = getDtsOutput('mixin-with-exports.module.scss');
expect(dts).toContain('card');
expect(dts).toContain('cardRadius');
expect(dts).toContain('animationDuration');
});
});
describe('extend-with-exports.module.scss (Sass @extend / placeholder selectors)', () => {
it('merges @extend selectors and strips :export when preserveIcssExports is false', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'extend-with-exports.module.scss');
const css: string = getCssOutput('extend-with-exports.module.scss');
// Placeholder %button-base should not appear literally; its rules should be merged
expect(css).not.toContain('%button-base');
expect(css).toContain('.primaryButton');
expect(css).toContain('.dangerButton');
expect(css).not.toContain(':export');
});
it('preserves :export alongside @extend-merged output when preserveIcssExports is true', async () => {
const { processor } = createProcessor(terminalProvider, { preserveIcssExports: true });
await compileFixtureAsync(processor, 'extend-with-exports.module.scss');
const css: string = getCssOutput('extend-with-exports.module.scss');
expect(css).toContain(':export');
expect(css).toContain('.primaryButton');
expect(css).not.toContain('%button-base');
});
it('generates .d.ts with class names and :export values for @extend file', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'extend-with-exports.module.scss');
const dts: string = getDtsOutput('extend-with-exports.module.scss');
expect(dts).toContain('primaryButton');
expect(dts).toContain('dangerButton');
expect(dts).toContain('colorPrimary');
expect(dts).toContain('colorDanger');
});
});
describe('JS shim files', () => {
it('emits a CommonJS shim for a module file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'commonjs' }]
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const shim: string = getJsShimOutput('classes-and-exports.module.scss');
// CJS module shim re-exports from the CSS file and mirrors it as .default
expect(shim).toContain(`require("./classes-and-exports.module.css")`);
expect(shim).toContain('module.exports.default = module.exports');
});
it('emits an ESM shim for a module file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'esnext' }]
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const shim: string = getJsShimOutput('classes-and-exports.module.scss');
// ESM module shim re-exports the default from the CSS file
expect(shim).toBe(`export { default } from "./classes-and-exports.module.css";`);
});
it('emits a CommonJS shim for a non-module (global) file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'commonjs' }],
// Register the .global.scss extension so the processor classifies it correctly
nonModuleFileExtensions: ['.global.scss']
});
await compileFixtureAsync(processor, 'global-styles.global.scss');
const shim: string = getJsShimOutput('global-styles.global.scss');
// CJS non-module shim: side-effect require only
expect(shim).toBe(`require("./global-styles.global.css");`);
});
it('emits an ESM shim for a non-module (global) file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'esnext' }],
nonModuleFileExtensions: ['.global.scss']
});
await compileFixtureAsync(processor, 'global-styles.global.scss');
const shim: string = getJsShimOutput('global-styles.global.scss');
// ESM non-module shim: side-effect import only
expect(shim).toBe(`import "./global-styles.global.css";export {};`);
});
it('does not emit a shim when shimModuleFormat is undefined', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: undefined }]
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
// Only the CSS and DTS files should be written - no .js shim
const shimPaths: string[] = getAllWrittenPathsMatching('.module.scss.js');
expect(shimPaths).toHaveLength(0);
});
it('writes shims to each configured cssOutputFolder independently', async () => {
const CSS_FOLDER_ESM: string = '/fake/output/css-esm';
const CSS_FOLDER_CJS: string = '/fake/output/css-cjs';
const cssOutputFolders: ICssOutputFolder[] = [
{ folder: CSS_FOLDER_ESM, shimModuleFormat: 'esnext' },
{ folder: CSS_FOLDER_CJS, shimModuleFormat: 'commonjs' }
];
const { processor } = createProcessor(terminalProvider, { cssOutputFolders });
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const esmShim: string = writtenFiles.get(`${CSS_FOLDER_ESM}/classes-and-exports.module.scss.js`)!;
const cjsShim: string = writtenFiles.get(`${CSS_FOLDER_CJS}/classes-and-exports.module.scss.js`)!;
expect(esmShim).toBe(`export { default } from "./classes-and-exports.module.css";`);
expect(cjsShim).toContain('module.exports.default = module.exports');
});
});
describe('global-only.module.scss (module file with only :global styles)', () => {
it('emits export {}; in the .d.ts when all styles are :global', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'global-only.module.scss');
const dts: string = getDtsOutput('global-only.module.scss');
expect(dts).toBe('export {};');
});
it('emits a side-effect ESM shim (no default re-export) when all styles are :global', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'esnext' }]
});
await compileFixtureAsync(processor, 'global-only.module.scss');
const shim: string = getJsShimOutput('global-only.module.scss');
expect(shim).toBe(`import "./global-only.module.css";export {};`);
});
it('emits a side-effect CJS shim (no module.exports assignment) when all styles are :global', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'commonjs' }]
});
await compileFixtureAsync(processor, 'global-only.module.scss');
const shim: string = getJsShimOutput('global-only.module.scss');
expect(shim).toBe(`require("./global-only.module.css");`);
});
it('emits compiled CSS with the :global styles applied', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'global-only.module.scss');
const css: string = getCssOutput('global-only.module.scss');
expect(css).toContain('.ms-Nav-group');
expect(css).toContain('.ms-Nav-link');
});
});
describe('simple.module.sass (indented Sass syntax)', () => {
it('compiles indented Sass syntax to CSS correctly', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'simple.module.sass');
const css: string = getCssOutput('simple.module.sass');
expect(css).toContain('.exampleClass');
expect(css).toContain('color: red');
expect(css).toContain('.exampleHeading');
expect(css).toContain('font-weight: bold');
});
it('generates .d.ts with class names from indented Sass', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'simple.module.sass');
const dts: string = getDtsOutput('simple.module.sass');
expect(dts).toContain('exampleClass');
expect(dts).toContain('exampleHeading');
expect(dts).toContain('export default styles');
});
it('emits an ESM shim for an indented Sass module file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'esnext' }]
});
await compileFixtureAsync(processor, 'simple.module.sass');
const shim: string = getJsShimOutput('simple.module.sass');
expect(shim).toBe(`export { default } from "./simple.module.css";`);
});
});
describe('use-with-partial.module.scss (@use with local partial)', () => {
it('resolves variables from a @use partial in CSS output', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'use-with-partial.module.scss');
const css: string = getCssOutput('use-with-partial.module.scss');
// $brand-color from the partial should be resolved to its value
expect(css).toContain('#0078d4');
// $spacing-unit * 2 = 8px
expect(css).toContain('8px');
expect(css).toContain('.container');
expect(css).toContain('.header');
});
it('generates .d.ts with class names from a file using @use', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'use-with-partial.module.scss');
const dts: string = getDtsOutput('use-with-partial.module.scss');
expect(dts).toContain('container');
expect(dts).toContain('header');
expect(dts).toContain('export default styles');
});
});
describe('use-plain-css.module.scss (@use of a plain .css file)', () => {
it('resolves a plain .css file referenced via @use with an explicit extension', async () => {
const { processor, logger } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'use-plain-css.module.scss');
// The @use must resolve without "Can't find stylesheet to import."
expect(logger.errors).toHaveLength(0);
const css: string = getCssOutput('use-plain-css.module.scss');
// Rules from the plain .css file should be inlined into the output
expect(css).toContain('.token-base');
expect(css).toContain('#0078d4');
expect(css).toContain('.container');
});
it('resolves a plain .css file referenced via @use without an explicit extension', async () => {
const { processor, logger } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'use-plain-css-extensionless.module.scss');
// Extensionless loads must fall back to the `.css` candidate, matching dart-sass
expect(logger.errors).toHaveLength(0);
const css: string = getCssOutput('use-plain-css-extensionless.module.scss');
expect(css).toContain('.token-base');
expect(css).toContain('#0078d4');
expect(css).toContain('.container');
});
});
describe('global-styles.global.sass (.global.sass non-module file)', () => {
it('compiles indented Sass syntax to plain CSS for a .global.sass file', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'global-styles.global.sass');
const css: string = getCssOutput('global-styles.global.sass');
expect(css).toContain('body');
expect(css).toContain('h1');
// $heading-size should be resolved to its value
expect(css).toContain('24px');
expect(css).toContain('#333');
});
it('emits export {}; in the .d.ts for a .global.sass file', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'global-styles.global.sass');
const dts: string = getDtsOutput('global-styles.global.sass');
expect(dts).toBe('export {};');
});
it('emits a side-effect ESM shim for a .global.sass file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'esnext' }]
});
await compileFixtureAsync(processor, 'global-styles.global.sass');
const shim: string = getJsShimOutput('global-styles.global.sass');
expect(shim).toBe(`import "./global-styles.global.css";export {};`);
});
});
describe('css-module.module.css (plain CSS as CSS module input)', () => {
it('generates .d.ts with class names from a .module.css input file', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'css-module.module.css');
const dts: string = getDtsOutput('css-module.module.css');
expect(dts).toContain('root');
expect(dts).toContain('header');
expect(dts).toContain('export default styles');
});
it('passes CSS through the pipeline unchanged for a .module.css input file', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'css-module.module.css');
const css: string = getCssOutput('css-module.module.css');
expect(css).toContain('.root');
expect(css).toContain('.header');
expect(css).toContain('display: flex');
});
it('does not emit a JS shim for a .module.css input file', async () => {
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'esnext' }]
});
await compileFixtureAsync(processor, 'css-module.module.css');
// .css inputs cannot have a shim (the shim would reference itself)
const shimPaths: string[] = getAllWrittenPathsMatching('.module.css.js');
expect(shimPaths).toHaveLength(0);
});
});
describe('silenceDeprecations option', () => {
it('throws at construction time when given an unknown deprecation code', () => {
expect(() =>
createProcessor(terminalProvider, { silenceDeprecations: ['not-a-real-deprecation-code'] })
).toThrow('Unknown deprecation code: not-a-real-deprecation-code');
});
});
describe('ignoreDeprecationsInDependencies option', () => {
it('emits deprecation warnings from a dependency partial by default', async () => {
const { processor, logger } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'use-partial-with-color-deprecation.module.scss');
expect(logger.errors).toHaveLength(0);
expect(terminalProvider.getWarningOutput()).toContain('Deprecation Warning:');
});
it('suppresses deprecation warnings from a dependency partial when ignoreDeprecationsInDependencies is true', async () => {
const { processor, logger } = createProcessor(terminalProvider, {
ignoreDeprecationsInDependencies: true
});
await compileFixtureAsync(processor, 'use-partial-with-color-deprecation.module.scss');
expect(logger.errors).toHaveLength(0);
expect(terminalProvider.getWarningOutput()).not.toContain('Deprecation Warning:');
});
});
describe('non-module (global) files', () => {
it('emits plain compiled CSS for a .global.scss file', async () => {
const { processor } = createProcessor(terminalProvider, {
nonModuleFileExtensions: ['.global.scss']
});
await compileFixtureAsync(processor, 'global-styles.global.scss');
const css: string = getCssOutput('global-styles.global.scss');
// Variables should be resolved; selectors should be present
expect(css).toContain('body');
expect(css).toContain('h1');
expect(css).toContain('font-family');
expect(css).not.toContain('$body-font');
});
it('emits export {}; in the .d.ts for a non-module file', async () => {
const { processor } = createProcessor(terminalProvider, {
nonModuleFileExtensions: ['.global.scss']
});
await compileFixtureAsync(processor, 'global-styles.global.scss');
const dts: string = getDtsOutput('global-styles.global.scss');
expect(dts).toBe('export {};');
});
});
describe('multiple output folders', () => {
it('writes .d.ts to every configured dtsOutputFolder', async () => {
const DTS_FOLDER_A: string = '/fake/output/dts-a';
const DTS_FOLDER_B: string = '/fake/output/dts-b';
const { processor } = createProcessor(terminalProvider, {
dtsOutputFolders: [DTS_FOLDER_A, DTS_FOLDER_B]
});
await compileFixtureAsync(processor, 'export-only.module.scss');
const dtsA: string = writtenFiles.get(`${DTS_FOLDER_A}/export-only.module.scss.d.ts`)!;
const dtsB: string = writtenFiles.get(`${DTS_FOLDER_B}/export-only.module.scss.d.ts`)!;
expect(dtsA).toBeDefined();
expect(dtsA).toEqual(dtsB);
});
it('writes CSS to every configured cssOutputFolder', async () => {
const CSS_FOLDER_A: string = '/fake/output/css-a';
const CSS_FOLDER_B: string = '/fake/output/css-b';
const { processor } = createProcessor(terminalProvider, {
cssOutputFolders: [
{ folder: CSS_FOLDER_A, shimModuleFormat: undefined },
{ folder: CSS_FOLDER_B, shimModuleFormat: undefined }
]
});
await compileFixtureAsync(processor, 'export-only.module.scss');
const cssA: string = writtenFiles.get(`${CSS_FOLDER_A}/export-only.module.css`)!;
const cssB: string = writtenFiles.get(`${CSS_FOLDER_B}/export-only.module.css`)!;
expect(cssA).toBeDefined();
expect(cssA).toEqual(cssB);
});
});
describe('postProcessCssAsync', () => {
it('passes compiled CSS through the post-processor callback', async () => {
const postProcessed: string[] = [];
const { processor } = createProcessor(terminalProvider, {
postProcessCssAsync: async (css: string) => {
postProcessed.push(css);
return css.replace(/color:/g, 'color: /* post-processed */');
}
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
// The callback should have been called with the raw CSS
expect(postProcessed.length).toBe(1);
expect(postProcessed[0]).toContain('color:');
// The emitted CSS should reflect the transformation
const css: string = getCssOutput('classes-and-exports.module.scss');
expect(css).toContain('color: /* post-processed */');
});
it('post-processor runs after postcss-modules strips :export', async () => {
const seenCss: string[] = [];
const { processor } = createProcessor(terminalProvider, {
postProcessCssAsync: async (css: string) => {
seenCss.push(css);
return css;
}
});
await compileFixtureAsync(processor, 'export-only.module.scss');
// With preserveIcssExports: false (default), the CSS seen by the callback
// should already have the :export block stripped
expect(seenCss[0]).not.toContain(':export');
});
it('post-processor receives the original CSS including :export when preserveIcssExports is true', async () => {
const seenCss: string[] = [];
const { processor } = createProcessor(terminalProvider, {
preserveIcssExports: true,
postProcessCssAsync: async (css: string) => {
seenCss.push(css);
return css;
}
});
await compileFixtureAsync(processor, 'export-only.module.scss');
expect(seenCss[0]).toContain(':export');
});
});
describe('doNotTrimOriginalFileExtension', () => {
it('strips the source extension by default (doNotTrimOriginalFileExtension: false)', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
// Default: "classes-and-exports.module.scss" → "classes-and-exports.module.css"
const css: string = writtenFiles.get(`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.css`)!;
expect(css).toBeDefined();
expect(writtenFiles.has(`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.scss.css`)).toBe(false);
});
it('preserves the source extension when doNotTrimOriginalFileExtension is true', async () => {
const { processor } = createProcessor(terminalProvider, { doNotTrimOriginalFileExtension: true });
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
// "classes-and-exports.module.scss" → "classes-and-exports.module.scss.css"
const css: string = writtenFiles.get(`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.scss.css`)!;
expect(css).toBeDefined();
expect(writtenFiles.has(`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.css`)).toBe(false);
});
it('uses the .scss.css filename in JS shims when doNotTrimOriginalFileExtension is true', async () => {
const { processor } = createProcessor(terminalProvider, {
doNotTrimOriginalFileExtension: true,
cssOutputFolders: [{ folder: CSS_OUTPUT_FOLDER, shimModuleFormat: 'commonjs' }]
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const shim: string = writtenFiles.get(`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.scss.js`)!;
expect(shim).toContain(`require("./classes-and-exports.module.scss.css")`);
});
it('the CSS content is the same regardless of doNotTrimOriginalFileExtension', async () => {
const { processor: processorDefault } = createProcessor(terminalProvider);
await compileFixtureAsync(processorDefault, 'classes-and-exports.module.scss');
const cssDefault: string = writtenFiles.get(`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.css`)!;
writtenFiles.clear();
const { processor: processorPreserve } = createProcessor(terminalProvider, {
doNotTrimOriginalFileExtension: true
});
await compileFixtureAsync(processorPreserve, 'classes-and-exports.module.scss');
const cssPreserve: string = writtenFiles.get(
`${CSS_OUTPUT_FOLDER}/classes-and-exports.module.scss.css`
)!;
expect(cssDefault).toEqual(cssPreserve);
});
});
describe('error reporting', () => {
it('emits an error for invalid SCSS syntax', async () => {
const { processor, logger } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'invalid.module.scss');
expect(logger.errors.length).toBeGreaterThan(0);
});
});
describe('sourceMap option', () => {
it('emits .css.map and sourceMappingURL comment when sourceMap is true', async () => {
const { processor } = createProcessor(terminalProvider, { sourceMap: true });
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
const mapPaths: string[] = getAllWrittenPathsMatching('.css.map');
expect(mapPaths).toHaveLength(1);
const css: string = getCssOutput('classes-and-exports.module.scss');
expect(css).toMatch(/\/\*# sourceMappingURL=classes-and-exports\.module\.css\.map \*\//);
const mapJson: string = getWrittenFile('classes-and-exports.module.css.map');
const parsedMap: {
version: number;
mappings: string;
sources: string[];
} = JSON.parse(mapJson);
expect(parsedMap.version).toBe(3);
expect(parsedMap.mappings).toBeTruthy();
expect(parsedMap.sources).toHaveLength(1);
expect(parsedMap.sources[0]).toMatch(/classes-and-exports\.module\.scss$/);
});
it('emits a valid .css.map when the entry file @uses a partial (Linux/macOS regression)', async () => {
// use-with-partial.module.scss uses @use 'partial', which goes through loadAsync.
// Without sourceMapUrl on the ImporterResult, sass-embedded falls back to a data: URL
// for the partial in the source map; heftUrlToPath then crashes on Linux/macOS.
const { processor } = createProcessor(terminalProvider, { sourceMap: true });
await compileFixtureAsync(processor, 'use-with-partial.module.scss');
const mapPaths: string[] = getAllWrittenPathsMatching('.css.map');
expect(mapPaths).toHaveLength(1);
const mapJson: string = getWrittenFile('use-with-partial.module.css.map');
const parsedMap: { version: number; mappings: string; sources: string[] } = JSON.parse(mapJson);
expect(parsedMap.version).toBe(3);
expect(parsedMap.mappings).toBeTruthy();
// Both the entry file and the partial must resolve to real paths, not data: URLs
expect(parsedMap.sources.every((s: string) => !s.startsWith('data:'))).toBe(true);
});
it('does not emit .css.map or sourceMappingURL comment by default', async () => {
const { processor } = createProcessor(terminalProvider);
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
expect(getAllWrittenPathsMatching('.css.map')).toHaveLength(0);
expect(getCssOutput('classes-and-exports.module.scss')).not.toContain('sourceMappingURL');
});
it('uses the correct map filename when doNotTrimOriginalFileExtension is true', async () => {
const { processor } = createProcessor(terminalProvider, {
sourceMap: true,
doNotTrimOriginalFileExtension: true
});
await compileFixtureAsync(processor, 'classes-and-exports.module.scss');
// With doNotTrimOriginalFileExtension the CSS file is foo.scss.css, so the map is foo.scss.css.map
const mapPaths: string[] = getAllWrittenPathsMatching('.css.map');
expect(mapPaths).toHaveLength(1);
expect(mapPaths[0]).toMatch(/classes-and-exports\.module\.scss\.css\.map$/);
const css: string = getWrittenFile('classes-and-exports.module.scss.css');
expect(css).toMatch(/\/\*# sourceMappingURL=classes-and-exports\.module\.scss\.css\.map \*\//);
});
});
});