React 测试 [Jest] 问题 - 域选项是必需的

React Testing [Jest] problem - domain option is required

我构建了一个使用 Auth0 作为身份验证的 React 应用程序。 我正在尝试使用 Jest 实现测试套件以测试组件中的功能之一。

我想在 React 组件 Project 中测试一个 createProject() 函数, 只是看看函数执行后会不会报错。

这是我的测试代码:

import Project from '../components/Projects/index'
import { shallow } from 'enzyme'

describe('Project testing', () => {
    it('createProject should be working', () => {
        const wrapper = shallow(<Project />);
        const instance = wrapper.instance();
        instance.createProject();
        expect(instance.createProject()).toHaveBeenCalled();
    })
})

我运行测试后,收到如下快照的错误信息: Error message snapshot

这是我的 Auth.js

import auth0 from 'auth0-js'

class Auth {
    constructor() {
        this.auth0 = new auth0.WebAuth({
            // the following three lines MUST be updated
            domain: process.env.REACT_APP_AUTH0_DOMAIN,
            audience: `https://${process.env.REACT_APP_AUTH0_DOMAIN}/userinfo`,
            clientID: process.env.REACT_APP_AUTH0_CLIENT_ID,
            redirectUri: `${process.env.REACT_APP_BASE_URL}/callback`,
            responseType: 'token id_token',
            scope: 'openid email profile',
        })

        this.getProfile = this.getProfile.bind(this)
        this.handleAuthentication = this.handleAuthentication.bind(this)
        this.isAuthenticated = this.isAuthenticated.bind(this)
        this.signIn = this.signIn.bind(this)
        this.signOut = this.signOut.bind(this)
    }

    getProfile() {
        return this.profile
    }

    getIdToken() {
        return this.idToken
    }

    isAuthenticated() {
        return new Date().getTime() < this.expiresAt
    }

    signIn() {
        this.auth0.authorize({}, (err, authResult) => {
            if (err) this.localLogout()
            else {
                this.localLogin(authResult)
                this.accessToken = authResult.accessToken
            }
        })
    }

    handleAuthentication() {
        return new Promise((resolve, reject) => {
            this.auth0.parseHash((err, authResult) => {
                if (err) {
                    alert(err.errorDescription)
                    this.signOut()
                    return reject(err)
                }
                if (!authResult || !authResult.idToken) {
                    return reject(err)
                }
                this.setSession(authResult)
                resolve()
            })
        })
    }

    setSession(authResult) {
        this.idToken = authResult.idToken
        this.profile = authResult.idTokenPayload
        // set the time that the id token will expire at
        this.expiresAt = authResult.idTokenPayload.exp * 1000
    }

    signOut() {
        // clear id token, profile, and expiration
        this.auth0.logout({
            returnTo: process.env.REACT_APP_BASE_URL,
            clientID: process.env.REACT_APP_AUTH0_CLIENT_ID,
        })
    }

    silentAuth() {
        return new Promise((resolve, reject) => {
            this.auth0.checkSession({}, (err, authResult) => {
                if (err) return reject(err)
                this.setSession(authResult)
                resolve()
            })
        })
    }
}

const auth0Client = new Auth()

export default auth0Client

我的 Auth0 域、客户端 ID 等都在 .env 文件中定义。

有人知道如何在 Jest 测试中解决这个问题吗?

在开始实例化组件之前,您需要定义自定义 process.env 属性:

beforeAll(() => {
  process.env = Object.assign(process.env, {
    REACT_APP_AUTH0_DOMAIN: 'foo',
    REACT_APP_AUTH0_CLIENT_ID: 'bar',
    REACT_APP_BASE_URL: 'baz'
  });
});

(我不确定是否定义了 REACT_APP_BASE_URL

我遇到了完全相同的问题。正如迈克尔所说,这是因为我们的测试中没有定义环境变量。您可以使用 Jest 的 setupFiles 功能解决该问题。此文件列表在每次测试之前获取 运行 一次,以设置测试环境。

我在这个 post () 中遵循了 Serhan 的回答,因为我不想公开我们的 .env 文件,但您也可以在设置中定义环境变量文件本身(不需要 dotenv npm 包)。

您可以查看此 post 以获得更多答案: