[英]How do I overcome build-time errors due to relative paths and custom imports with Next.JS applications?
[英]How do I ignore CSS Module imports in a Next.js component that cause parse errors in unit tests
我在我的 Next.js 項目(我是 Next.js 的新手)中使用 CSS 模塊並使用Riteway進行測試。 當我為 React 組件運行單元測試時,任何導入 CSS 模塊的組件都會失敗並出現 SyntaxError,因為它無法解析正在導入的 CSS 文件。 我已經必須創建一個.babelrc
文件來處理測試中的 JSX 解析,以便它復制 Next.js 配置( { "presets": ["next/babel"], "plugins": [] }
)並使用-r @babel/register
激活它-r @babel/register
作為我的測試命令的一部分,但它似乎沒有處理 CSS 模塊。
如何將我的代碼配置為至少不會阻塞 CSS 模塊導入並使其在styles
中import styles from './styles.module.css';
是一個空的 object 以便所有styles.myClass
引用都不會中斷? 不幸的是,似乎沒有任何關於與其他運行上下文(如單元測試)共享 Babel 配置的文檔,只有在需要時如何自定義 Babel 配置。
組件文件
import React from 'react';
import styles from './styles.module.css'`;
export default () => (
<div className={styles.root}>
Content
</div>
);
組件 CSS 模塊
.root {
background: green;
}
組件測試文件
import React from 'react';
import { describe } from 'riteway';
import render from 'riteway/render-component';
import MyComponent from './component.jsx';
describe('<MyComponent>', async assert => {
const $ = render(<MyComponent />);
assert({
given: 'rendering the component',
should: 'render',
actual: $('body > div').length,
expected: 1,
});
});
測試命令
$ NODE_ENV=test riteway -r @babel/register -r regenerator-runtime src/path/to/component.test.jsx
測試命令結果
(function (exports, require, module, __filename, __dirname) { .root {
^
SyntaxError: Unexpected token '.'
at new Script (vm.js:84:7)
at createScript (vm.js:258:10)
at Object.runInThisContext (vm.js:306:10)
at Module._compile (internal/modules/cjs/loader.js:880:26)
at Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Object.newLoader [as .js] (/path/to/app/node_modules/pirates/lib/index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
進一步挖掘,有一個ignore-styles
package 可以用作-r @babel/register -r ignore-styles
,這似乎使它起作用。 不確定這是否是最佳選擇,但它解除了我的阻礙。 我仍然對其他答案持開放態度。
您需要將babel-plugin-module-name-mapper
添加到.babelrc
的plugins
中。
[
"module-name-mapper",
{
"moduleNameMapper": {
"\\.css$": "<rootDir>/src/helpers/mock/style-mock.js"
}
}
]
這里style-mock.js
只是簡單地導出一個空的 object。
module.exports = {};
這將做的是,它將用空的 object 替換所有 css,因為無論如何您都不應該使用單元測試來測試 styles。 (您應該為此使用視覺回歸測試。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.