【发布时间】: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 测试中解决这个问题吗?
【问题讨论】:
-
请以文本形式提供minimal reproducible example。
标签: javascript reactjs unit-testing jestjs auth0