简体   繁体   English

如何使用 Next.js 在测试中加载环境变量?

[英]How to load environment variable in tests with Next.js?

I'm trying to run a simple test with JavaScript as below.我正在尝试使用 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)
  })
});

When running the tests I'm getting this error运行测试时,我收到此错误

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

How do I make this error go away - surely it shouldn't require Google Analytics code given the above, it's not in production when running the test?我如何使这个错误消失 - 鉴于上述情况,它肯定不需要谷歌分析代码,运行测试时它不在生产中?

Update更新

So I need to make sure the .env file is being loaded!所以我需要确保.env文件正在加载!

In my package.json I've got this Jest setup:在我的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
      }
    }
  },

updated code to use jest.setup - can't get env to load更新代码以使用 jest.setup - 无法加载 env

So所以

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"]

};

The environment variable files is here:环境变量文件在这里:

process.env.NEXT_PUBLIC_GA_TRACKING_ID=xxx

And this is the code that is not loading the environment variables properly.这是未正确加载环境变量的代码。

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

This message means that the trackingId is not defined.此消息表示未定义trackingId As you can see it read from the process.env .如您所见,它是从process.env读取的。 You need to create this file in the root of your project and call it .env .您需要在项目的根目录中创建此文件并将其.env Note that the dot is at the beginning of the filename.请注意,点位于文件名的开头。 The content of the file should be as follow:文件内容应如下所示:

NEXT_PUBLIC_GA_TRACKING_ID=insert-key-here

If your env file is not being read by jest you can do the following:如果 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'});

You can also check this article for more details.您还可以查看这篇文章以了解更多详细信息。

During your tests you can leverage loadEnvConfig from @next/env to make sure your environment variables are loaded the same way Next.js does.在您的测试期间,您可以利用@next/env loadEnvConfig来确保您的环境变量以与 Next.js 相同的方式加载。

First setup a .env.test to be used during the tests.首先设置一个.env.test在测试期间使用。

NEXT_PUBLIC_GA_TRACKING_ID=ga-test-id

Next, create a Jest global setup file if you don't have one yet, and reference it in your jest.config.js .接下来,如果您还没有 Jest 全局设置文件,请创建一个 Jest 全局设置文件,并在您的jest.config.js引用它。

// jest.config.js

module.exports = {
    //...
    setupFilesAfterEnv: ['./jest.setup.js'],
};

Then add the following code into your Jest global setup file.然后将以下代码添加到 Jest 全局设置文件中。

// jest.setup.js
import { loadEnvConfig } from '@next/env'

loadEnvConfig(process.cwd())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM