Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(component-testing): correctly import components with css from third party libraries #1023

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/bundle/test-transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import * as nodePath from "node:path";
import * as babel from "@babel/core";
import { addHook } from "pirates";
import { TRANSFORM_EXTENSIONS, JS_EXTENSION_RE } from "./constants";
import { requireModuleSync } from "../utils/module";
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Helper in order to be able to test require


import type { NodePath, PluginObj, TransformOptions } from "@babel/core";
import type { ImportDeclaration } from "@babel/types";

const STYLE_EXTESTION_RE = /\.(css|less|scss|sass|styl|stylus|pcss)$/;
const IGNORE_STYLE_ERRORS = ["Unexpected token"];

export const setupTransformHook = (opts: { removeNonJsImports?: boolean } = {}): VoidFunction => {
const transformOptions: TransformOptions = {
browserslistConfigFile: false,
Expand Down Expand Up @@ -34,6 +38,15 @@ export const setupTransformHook = (opts: { removeNonJsImports?: boolean } = {}):

if (extname && !extname.match(JS_EXTENSION_RE)) {
path.remove();
return;
}

try {
requireModuleSync(path.node.source.value);
} catch (err) {
if (shouldIgnoreImportError(err as Error)) {
path.remove();
}
}
},
},
Expand All @@ -52,3 +65,19 @@ export const setupTransformHook = (opts: { removeNonJsImports?: boolean } = {}):

return revertTransformHook;
};

function shouldIgnoreImportError(err: Error): boolean {
const shouldIgnoreImport = IGNORE_STYLE_ERRORS.some(ignoreImportErr => {
return (err as Error).message.startsWith(ignoreImportErr);
});

if (!shouldIgnoreImport) {
return false;
}

const firstStackFrame = (err as Error).stack?.split("\n")[0] || "";
const filePath = firstStackFrame.split(":")[0];
const isStyleFilePath = STYLE_EXTESTION_RE.test(filePath);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I get an error from import css first frame in stack looks like: /Users/.../some.css:100500.


return isStyleFilePath;
}
4 changes: 4 additions & 0 deletions src/utils/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ export const requireModule = async <T = unknown>(modulePath: string): Promise<T>

return require(isModuleLocal ? path.resolve(modulePath) : modulePath);
};

export const requireModuleSync = (modulePath: string): unknown => {
return require(modulePath);
};
81 changes: 67 additions & 14 deletions test/src/test-reader/test-transformer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as pirates from "pirates";
import sinon, { SinonStub } from "sinon";
import proxyquire from "proxyquire";
import { setupTransformHook, TRANSFORM_EXTENSIONS } from "../../../src/test-reader/test-transformer";

describe("test-transformer", () => {
Expand Down Expand Up @@ -59,29 +60,81 @@ describe("test-transformer", () => {
});
});

[true, false].forEach(removeNonJsImports => {
describe(`should ${removeNonJsImports ? "" : "not "}remove non-js imports`, () => {
[".css", ".less", ".scss", ".jpg", ".png", ".woff"].forEach(extName => {
it(`asset with extension: "${extName}"`, () => {
describe("'removeNonJsImports' option", () => {
[true, false].forEach(removeNonJsImports => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just move to common describe

describe(`should ${removeNonJsImports ? "" : "not "}remove non-js imports`, () => {
[".css", ".less", ".scss", ".jpg", ".png", ".woff"].forEach(extName => {
it(`asset with extension: "${extName}"`, () => {
let transformedCode;
const fileName = `some${extName}`;
(pirates.addHook as SinonStub).callsFake(cb => {
transformedCode = cb(`import "${fileName}"`, fileName);
});

setupTransformHook({ removeNonJsImports });

const expectedCode = ['"use strict";'];

if (!removeNonJsImports) {
expectedCode.push("", `require("some${extName}");`);
}

expectedCode.push("//# sourceMappingURL=");

assert.match(transformedCode, expectedCode.join("\n"));
});
});
});
});

describe("should remove third party import with error from", () => {
[".css", ".less", ".scss", ".sass", ".styl", ".stylus", ".pcss"].forEach(extName => {
it(`${extName} style file`, () => {
const moduleName = "some-module";
const error = { message: "Unexpected token {", stack: `foo${extName}:100500\nbar\nqux` };

const { setupTransformHook } = proxyquire("../../../src/test-reader/test-transformer", {
"../bundle": proxyquire.noCallThru().load("../../../src/bundle/test-transformer", {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I use two proxyquire in order to correctly check the logic. Didn't find another solution.

"../utils/module": {
requireModuleSync: sandbox.stub().withArgs(moduleName).throws(error),
},
}),
});

let transformedCode;
const fileName = `some${extName}`;

(pirates.addHook as SinonStub).callsFake(cb => {
transformedCode = cb(`import "${fileName}"`, fileName);
transformedCode = cb(`import "${moduleName}"`, moduleName);
});

setupTransformHook({ removeNonJsImports });
setupTransformHook({ removeNonJsImports: true });

const expectedCode = ['"use strict";'];
assert.notMatch(transformedCode, new RegExp(`require\\("${moduleName}"\\)`));
});
});
});

if (!removeNonJsImports) {
expectedCode.push("", `require("some${extName}");`);
}
it("should not remove third party import with error not from style file", () => {
const moduleName = "some-module";
const error = { message: "Some error", stack: `foo.js:100500\nbar\nqux` };

const { setupTransformHook } = proxyquire("../../../src/test-reader/test-transformer", {
"../bundle": proxyquire.noCallThru().load("../../../src/bundle/test-transformer", {
"../utils/module": {
requireModuleSync: sandbox.stub().withArgs(moduleName).throws(error),
},
}),
});

expectedCode.push("//# sourceMappingURL=");
let transformedCode;

assert.match(transformedCode, expectedCode.join("\n"));
});
(pirates.addHook as SinonStub).callsFake(cb => {
transformedCode = cb(`import "${moduleName}"`, moduleName);
});

setupTransformHook({ removeNonJsImports: true });

assert.match(transformedCode, new RegExp(`require\\("${moduleName}"\\)`));
});
});
});
Expand Down
Loading