嗯,我有一个有趣的案例...
我正在尝试测试使用Okta SDK登录用户的Vuex操作。没什么特别的。但是在测试级别,我一直想抓住这个想法。我的意思是,我只想知道函数是否已被调用,而不是这里的代码:
服务:
const signIn = async ({ username, password }) => {
const response = await authClient.signIn({ username, password })
if (response.status === 'SUCCESS') {
const tokens = await authClient.token.getWithoutPrompt({
responseType: 'id_token',
sessionToken: response.sessionToken
})
authClient.tokenManager.add('idToken', tokens.tokens.idToken)
return response
}
}
动作:
async logIn({ commit }, { username, password }) {
const loginData = await signIn({ username, password })
commit(mutationTypes.setUserData, {
...loginData.user.profile
})
}
测试:
const authClient = {
signIn() {
return new Promise(resolve => resolve())
},
token: {
getWithoutPrompt() {
return new Promise(resolve => resolve())
}
},
tokenManager: {
add() {
return new Promise(resolve => resolve())
}
}
}
jest.mock('authClient', () => authClient)
it('Auth -> actions.signIn', async () => {
const commit = jest.fn()
const username = 'user'
const password = 'pass'
await actions.signIn({ commit }, { username, password })
expect(authClient.signIn).toHaveBeenCalled()
expect(authClient.token.getWithoutPrompt).toHaveBeenCalled()
expect(authClient.tokenManager.add).toHaveBeenCalled()
expect(commit).toHaveBeenCalled()
})