[英]How to load environment variable in tests with Next.js?
我正在嘗試使用 JavaScript 運行一個簡單的測試,如下所示。
import React from 'react';
import Customization from 'components/onboarding/customization';
import '@testing-library/jest-dom';
import { render, screen, fireEvent } from '@testing-library/react';
describe('customization render', () => {
it('should render the Hero page with no issue', () => {
render(<Customization />);
const heading = screen.getByText(
/All the Moodmap at one place!/i
);
expect(heading).toBeInTheDocument();
});
it("should call onCLick method on click", () => {
const mockOnClick = jest.fn()
const {container} = render(<Customization />);
const button = getByTestId(container, 'alreadyDownloaded');
fireEvent.click(button);
expect(mockOnClick).toHaveBeenCalledTimes(1)
// const mockOnClick = jest.fn()
// const utils = render(<Customization onClick={mockOnClick} />)
// fireEvent.click(screen.getByText(/already downloaded ⟶/i))
// expect(mockOnClick).toHaveBeenCalledTimes(1)
})
});
運行測試時,我收到此錯誤
No google analytics trackingId defined
8 | debug: process.env.NODE_ENV !== 'production',
9 | plugins: [
> 10 | googleAnalyticsPlugin({
| ^
11 | trackingId: process.env.NEXT_PUBLIC_GA_TRACKING_ID,
12 | }),
我如何使這個錯誤消失 - 鑒於上述情況,它肯定不需要谷歌分析代碼,運行測試時它不在生產中?
所以我需要確保.env
文件正在加載!
在我的package.json
我有這個 Jest 設置:
"jest": {
"testMatch": [
"**/?(*.)(spec|test).?(m)js?(x)"
],
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
"moduleDirectories": [
"node_modules",
"src"
],
"rootDir": "src",
"moduleFileExtensions": [
"js",
"jsx",
"mjs"
],
"transform": {
"^.+\\.m?jsx?$": "babel-jest"
},
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
},
所以
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import "@testing-library/jest-dom";
configure({
adapter: new Adapter()
});
module.exports = {
testMatch: [
"**/?(*.)(spec|test).?(m)js?(x)"
],
moduleNameMapper: {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
moduleDirectories: [
"node_modules",
"src"
],
rootDir: "src",
moduleFileExtensions: [
"js",
"jsx",
"mjs"
],
transform: {
"^.+\\.m?jsx?$": "babel-jest"
},
coverageThreshold: {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
},
setupFiles: ["../<rootDir>/.config.env.test"]
};
環境變量文件在這里:
process.env.NEXT_PUBLIC_GA_TRACKING_ID=xxx
這是未正確加載環境變量的代碼。
import Analytics from 'analytics';
import googleAnalyticsPlugin from '@analytics/google-analytics';
import Router from 'next/router';
// Initialize analytics and plugins
// Documentation: https://getanalytics.io
const analytics = Analytics({
debug: process.env.NODE_ENV !== 'production',
plugins: [
googleAnalyticsPlugin({
trackingId: process.env.NEXT_PUBLIC_GA_TRACKING_ID,
}),
],
});
此消息表示未定義trackingId
。 如您所見,它是從process.env
讀取的。 您需要在項目的根目錄中創建此文件並將其.env
。 請注意,點位於文件名的開頭。 文件內容應如下所示:
NEXT_PUBLIC_GA_TRACKING_ID=insert-key-here
如果 jest 沒有讀取您的 env 文件,您可以執行以下操作:
// In jest.config.js :
module.exports = {
....
setupFiles: ["<rootDir>/test/setup-tests.ts"]
}
// The file test/test-setup.ts:
import dotenv from 'dotenv';
dotenv.config({path: './config.env.test'});
您還可以查看這篇文章以了解更多詳細信息。
在您的測試期間,您可以利用@next/env
loadEnvConfig
來確保您的環境變量以與 Next.js 相同的方式加載。
首先設置一個.env.test
在測試期間使用。
NEXT_PUBLIC_GA_TRACKING_ID=ga-test-id
接下來,如果您還沒有 Jest 全局設置文件,請創建一個 Jest 全局設置文件,並在您的jest.config.js
引用它。
// jest.config.js
module.exports = {
//...
setupFilesAfterEnv: ['./jest.setup.js'],
};
然后將以下代碼添加到 Jest 全局設置文件中。
// jest.setup.js
import { loadEnvConfig } from '@next/env'
loadEnvConfig(process.cwd())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.