I have built a React app that is using Auth0 as Authentication. I am trying to implement test suit using Jest to test one of the functions in a component.
I want to test a createProject()
function in a React Component Project
,
just to see if the function would cause any error after execute.
Here is my test code:
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();
})
})
After I run the test, I received the error message of following snapshot: Error message snapshot
Here is my 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
My Auth0 domain, client ID, ..etc are all defined in .env file.
Anyone has any idea how to solve this problem on Jest testing ?