koel/resources/assets/js/services/authService.spec.ts

88 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-05-14 18:49:45 +00:00
import UnitTestCase from '@/__tests__/UnitTestCase'
import { expect, it } from 'vitest'
import type { UpdateCurrentProfileData } from '@/services'
import { authService, http } from '@/services'
2024-03-15 15:09:50 +00:00
import { useLocalStorage } from '@/composables'
2024-01-18 11:13:05 +00:00
import factory from '@/__tests__/factory'
import { userStore } from '@/stores'
2022-05-14 18:49:45 +00:00
new class extends UnitTestCase {
protected test () {
2024-03-15 15:09:50 +00:00
const { get: lsGet, set: lsSet } = useLocalStorage(false)
2022-05-14 18:49:45 +00:00
it('gets the token', () => {
2024-03-15 15:09:50 +00:00
lsSet('api-token', 'foo')
expect(authService.getApiToken()).toBe('foo')
2022-05-14 18:49:45 +00:00
})
it.each([['foo', true], [null, false]])('checks if the token exists', (token, exists) => {
2024-03-15 15:09:50 +00:00
lsSet('api-token', token)
2022-11-16 17:57:38 +00:00
expect(authService.hasApiToken()).toBe(exists)
2022-05-14 18:49:45 +00:00
})
it('sets the token', () => {
2022-11-16 17:57:38 +00:00
authService.setApiToken('foo')
2024-03-15 15:09:50 +00:00
expect(lsGet('api-token')).toBe('foo')
2022-05-14 18:49:45 +00:00
})
it('destroys the token', () => {
2024-03-15 15:09:50 +00:00
lsSet('api-token', 'foo')
2022-05-14 18:49:45 +00:00
authService.destroy()
2024-03-15 15:09:50 +00:00
expect(lsGet('api-token')).toBeNull()
2022-05-14 18:49:45 +00:00
})
2024-01-18 11:13:05 +00:00
it('logs in', async () => {
const postMock = this.mock(http, 'post').mockResolvedValue({
'audio-token': 'foo',
'token': 'bar',
2024-01-18 11:13:05 +00:00
})
await authService.login('john@doe.com', 'curry-wurst')
expect(postMock).toHaveBeenCalledWith('me', { email: 'john@doe.com', password: 'curry-wurst' })
})
it('logs out', async () => {
const deleteMock = this.mock(http, 'delete')
await authService.logout()
expect(deleteMock).toHaveBeenCalledWith('me')
})
it('gets profile', async () => {
const getMock = this.mock(http, 'get')
await authService.getProfile()
expect(getMock).toHaveBeenCalledWith('me')
})
it('updates profile', async () => {
userStore.state.current = factory('user', {
2024-01-18 11:13:05 +00:00
id: 1,
name: 'John Doe',
email: 'john@doe.com',
2024-01-18 11:13:05 +00:00
})
const updated = factory('user', {
2024-01-18 11:13:05 +00:00
id: 1,
name: 'Jane Doe',
email: 'jane@doe.com',
2024-01-18 11:13:05 +00:00
})
const putMock = this.mock(http, 'put').mockResolvedValue(updated)
const data: UpdateCurrentProfileData = {
current_password: 'curry-wurst',
name: 'Jane Doe',
email: 'jane@doe.com',
2024-01-18 11:13:05 +00:00
}
await authService.updateProfile(data)
expect(putMock).toHaveBeenCalledWith('me', data)
expect(userStore.current.name).toBe('Jane Doe')
expect(userStore.current.email).toBe('jane@doe.com')
})
2022-05-14 18:49:45 +00:00
}
}