【问题标题】:React Testing [Jest] problem - domain option is requiredReact 测试 [Jest] 问题 - 需要域选项
【发布时间】:2020-06-09 18:37:43
【问题描述】:

我已经构建了一个使用 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、..etc 都在 .env 文件中定义。

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

【问题讨论】:

标签: javascript reactjs unit-testing jestjs auth0


【解决方案1】:

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

我在这篇文章 (https://stackoverflow.com/a/57944454/8286893) 中关注了 Serhan 的回答,因为我不想暴露我们的 .env 文件,但是您也可以在设置文件本身中定义环境变量(不需要 dotenv npm包)。

您可以查看此帖子以获得更多答案:test process.env with Jest

【讨论】:

    【解决方案2】:

    在开始实例化组件之前,您需要定义您的自定义 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 是否已定义或未开箱即用。尝试不使用,如果仍然中断,请添加它。)

    【讨论】:

    • 感谢您的回答!我尝试添加 beforeAll() 并在 Object.assign 中包含所有 process.env 变量,但我仍然遇到同样的错误。 (我还包括了 REACT_APP_BASE_URL)
    • 您能否在测试中使用 console.log() 并查看包含的属性?
    • 我试过console.log(process.env),但没有打印出来。我认为错误发生在我做的线上import Project from '../components/Projects/index'
    • 嗯。屏幕截图显示了 auth0 构造函数中的错误。也许尝试直接在测试中而不是在 beforeAll 中设置这些?
    • 我尝试将代码放在 test('...') 块中,但仍然显示相同的错误。
    猜你喜欢
    • 2017-09-23
    • 2016-07-12
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2020-07-23
    • 2020-12-15
    • 2021-05-26
    相关资源
    最近更新 更多