Skip to content

Testing this plugin

Raimondo Mancino edited this page May 23, 2022 · 2 revisions

Running the tests

Note: if you are developing tests, please move to the testing branch first and then merge it with the associated feature/

We use Jest test suites.

However, since we're using Yarn, simply running jest may not work.

To support npm modules, the actual command we use for our tests is this:

$ yarn node --experimental-vm-modules $(yarn bin jest)

Testing the main class

This is the code I used for one of the test suites:

test(
	'Bundles sass sources from import statements',
	async function testSASSImport() {
		await expect(new Promise((ok, fail) => {
			const plugin = new ESBuildSASSModulesPlugin();

			const dir = p.dirname(p.resolve(PATH_SAMPLE_SIMPLE_SCSS, '../../'));

			const fakeEsb =
				{ async onResolve(filter, fn) {
					const
						{ path: pathSCSS
						, namespace: namespaceSCSS
						} = await fn(
						{ path: PATH_SAMPLE_SIMPLE_SCSS
						, kind: 'import-statement'
						, importer: p.resolve(PATH_SAMPLE_SIMPLE_JS)
						, resolveDir: dir
						}
					);

					expect(pathSCSS).toBe(p.resolve(PATH_SAMPLE_SIMPLE_SCSS));
					expect(namespaceSCSS)
						.toBe(ESBuildSASSModulesPlugin.namespace);

					const
						{ path: pathSASS
						, namespace: namespaceSASS
						} = await fn(
						{ path: PATH_SAMPLE_SIMPLE_SASS
						, kind: 'import-statement'
						, importer: p.resolve(PATH_SAMPLE_SIMPLE_JS)
						}
					);

					expect(pathSASS).toBe(p.resolve(PATH_SAMPLE_SIMPLE_SASS));
					expect(namespaceSASS)
						.toBe(ESBuildSASSModulesPlugin.namespace);
				}
				, onLoad(filter, fn) {
					ok(fn);
				}
				, async resolve(path) {
					if(path === PATH_SAMPLE_SIMPLE_SCSS) {
						return { path: p.resolve(PATH_SAMPLE_SIMPLE_SCSS) };
					}

					if(path === PATH_SAMPLE_SIMPLE_SASS) {
						return { path: p.resolve(PATH_SAMPLE_SIMPLE_SASS) };
					}
				}
				};

			expect(() => plugin.setup(fakeEsb)).not.toThrow();
		})
		.then(chainTestSASSbuild(
			PATH_SAMPLE_SIMPLE_SCSS,
			PATH_SAMPLE_SIMPLE_SCSS_COMPILED
		))
		.then(chainTestSASSbuild(
			PATH_SAMPLE_SIMPLE_SASS,
			PATH_SAMPLE_SIMPLE_SASS_COMPILED
		))).resolves.toBeTruthy();
	}
);

Basically, I used a fake esbuild object to test the correctness of the main behavior.

Testing the index file

test(
	'Builds a simple program',
	async function testSimpleBuild() {
		await testBuild(
			buildSimple(),
			PATH_SAMPLE_SIMPLE_JS_COMPILED
		);
	}
);

The testBuild() will chain an esbuild result (in this case, returned from buildSimple()) to a check that compares the produced outfile with a known compiled file (PATH_SAMPLE_SIMPLE_JS_COMPILED, in this case).

The list of PATH constants is found in test/constants.js. You can find a set of useful utils for tests in test/utils.js