如何使用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
}
}
},

更新代码以使用jest.setup-无法加载env

所以

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,
}),
],
});

您可以在测试中利用@next/env中的loadEnvConfig来确保环境变量的加载方式与Next.js相同。


首先设置要在测试中使用的.env.test

NEXT_PUBLIC_GA_TRACKING_ID=ga-test-id

接下来,创建一个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())

此消息表示未定义trackingId。正如您从process.env中看到的那样。您需要在项目的根目录中创建此文件,并将其命名为.env。请注意,点位于文件名的开头。文件的内容应如下:

NEXT_PUBLIC_GA_TRACKING_ID=insert-key-here

如果您的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'});

您也可以查看这篇文章了解更多详细信息。