Skip to content

Commit

Permalink
tests: vi.mocked for the typescript win
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Oct 14, 2024
1 parent 76cba51 commit de2f3bb
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 31 deletions.
17 changes: 7 additions & 10 deletions src/commands/login/actions.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { Mock } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { loginWithEmailAndPassword, loginWithOtp, loginWithToken } from './actions'
import { ofetch } from 'ofetch'
Expand All @@ -8,8 +7,6 @@ vi.mock('ofetch', () => ({
ofetch: vi.fn(),
}))

const mockedFetch = ofetch as unknown as Mock

describe('login actions', () => {
beforeEach(() => {
vi.clearAllMocks()
Expand All @@ -18,7 +15,7 @@ describe('login actions', () => {
describe('loginWithToken', () => {
it('should login successfully with a valid token', async () => {
const mockResponse = { data: 'user data' }
mockedFetch.mockResolvedValue(mockResponse)
vi.mocked(ofetch).mockResolvedValue(mockResponse)

const result = await loginWithToken('valid-token', 'eu')
expect(result).toEqual(mockResponse)
Expand All @@ -29,7 +26,7 @@ describe('login actions', () => {
response: { status: 401 },
data: { error: 'Unauthorized' },
}
mockedFetch.mockRejectedValue(mockError)
vi.mocked(ofetch).mockRejectedValue(mockError)

await expect(loginWithToken('invalid-token', 'eu')).rejects.toThrow(
new Error(`The token provided ${chalk.bold('inva*********')} is invalid: ${chalk.bold('401 Unauthorized')}
Expand All @@ -40,7 +37,7 @@ describe('login actions', () => {

it('should throw a network error if response is empty (network)', async () => {
const mockError = new Error('Network error')
mockedFetch.mockRejectedValue(mockError)
vi.mocked(ofetch).mockRejectedValue(mockError)

await expect(loginWithToken('any-token', 'eu')).rejects.toThrow(
'No response from server, please check if you are correctly connected to internet',
Expand All @@ -51,15 +48,15 @@ describe('login actions', () => {
describe('loginWithEmailAndPassword', () => {
it('should login successfully with valid email and password', async () => {
const mockResponse = { data: 'user data' }
mockedFetch.mockResolvedValue(mockResponse)
vi.mocked(ofetch).mockResolvedValue(mockResponse)

const result = await loginWithEmailAndPassword('[email protected]', 'password', 'eu')
expect(result).toEqual(mockResponse)
})

it('should throw a generic error for login failure', async () => {
const mockError = new Error('Network error')
mockedFetch.mockRejectedValue(mockError)
vi.mocked(ofetch).mockRejectedValue(mockError)

await expect(loginWithEmailAndPassword('[email protected]', 'password', 'eu')).rejects.toThrow(
'Error logging in with email and password',
Expand All @@ -70,15 +67,15 @@ describe('login actions', () => {
describe('loginWithOtp', () => {
it('should login successfully with valid email, password, and otp', async () => {
const mockResponse = { data: 'user data' }
mockedFetch.mockResolvedValue(mockResponse)
vi.mocked(ofetch).mockResolvedValue(mockResponse)

const result = await loginWithOtp('[email protected]', 'password', '123456', 'eu')
expect(result).toEqual(mockResponse)
})

it('should throw a generic error for login failure', async () => {
const mockError = new Error('Network error')
mockedFetch.mockRejectedValue(mockError)
vi.mocked(ofetch).mockRejectedValue(mockError)

await expect(loginWithOtp('[email protected]', 'password', '123456', 'eu')).rejects.toThrow(
'Error logging in with email, password and otp',
Expand Down
37 changes: 19 additions & 18 deletions src/commands/login/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ vi.mock('../../creds', () => ({

// Mocking the session module
vi.mock('../../session', () => {
let _cache
let _cache: Record<string, any> | null = null
const session = () => {
if (!_cache) {
_cache = {
Expand All @@ -48,6 +48,7 @@ vi.mock('../../utils', async () => {
...actualUtils,
konsola: {
ok: vi.fn(),
title: vi.fn(),
error: vi.fn(),
},
handleError: (error: Error, header = false) => {
Expand Down Expand Up @@ -83,15 +84,15 @@ describe('loginCommand', () => {
vi.resetAllMocks()
})
it('should prompt the user for email and password when login-with-email is selected', async () => {
select
vi.mocked(select)
.mockResolvedValueOnce('login-with-email') // For login strategy
.mockResolvedValueOnce('eu') // For region

input
vi.mocked(input)
.mockResolvedValueOnce('[email protected]') // For email
.mockResolvedValueOnce('123456') // For OTP code

password.mockResolvedValueOnce('test-password')
vi.mocked(password).mockResolvedValueOnce('test-password')

await loginCommand.parseAsync(['node', 'test'])

Expand All @@ -109,18 +110,18 @@ describe('loginCommand', () => {
})

it('should login with email and password if provided using login-with-email strategy', async () => {
select
vi.mocked(select)
.mockResolvedValueOnce('login-with-email') // For login strategy
.mockResolvedValueOnce('eu') // For region

input
vi.mocked(input)
.mockResolvedValueOnce('[email protected]') // For email
.mockResolvedValueOnce('123456') // For OTP code

password.mockResolvedValueOnce('test-password')
vi.mocked(password).mockResolvedValueOnce('test-password')

loginWithEmailAndPassword.mockResolvedValueOnce({ otp_required: true })
loginWithOtp.mockResolvedValueOnce({ access_token: 'test-token' })
vi.mocked(loginWithEmailAndPassword).mockResolvedValueOnce({ otp_required: true })
vi.mocked(loginWithOtp).mockResolvedValueOnce({ access_token: 'test-token' })

await loginCommand.parseAsync(['node', 'test'])

Expand All @@ -130,8 +131,8 @@ describe('loginCommand', () => {
})

it('should throw an error for invalid email and password', async () => {
select.mockResolvedValueOnce('login-with-email')
input.mockResolvedValueOnce('eu')
vi.mocked(select).mockResolvedValueOnce('login-with-email')
vi.mocked(input).mockResolvedValueOnce('eu')

const mockError = new Error('Error logging in with email and password')
loginWithEmailAndPassword.mockRejectedValueOnce(mockError)
Expand All @@ -155,10 +156,10 @@ describe('loginCommand', () => {
})

it('should login with token if token is provided using login-with-token strategy', async () => {
select.mockResolvedValueOnce('login-with-token')
password.mockResolvedValueOnce('test-token')
vi.mocked(select).mockResolvedValueOnce('login-with-token')
vi.mocked(password).mockResolvedValueOnce('test-token')
const mockUser = { email: '[email protected]' }
loginWithToken.mockResolvedValue({ user: mockUser })
vi.mocked(loginWithToken).mockResolvedValue({ user: mockUser })

await loginCommand.parseAsync(['node', 'test'])

Expand All @@ -178,7 +179,7 @@ describe('loginCommand', () => {
it('should login with a valid token', async () => {
const mockToken = 'test-token'
const mockUser = { email: '[email protected]' }
loginWithToken.mockResolvedValue({ user: mockUser })
vi.mocked(loginWithToken).mockResolvedValue({ user: mockUser })

await loginCommand.parseAsync(['node', 'test', '--token', mockToken])

Expand All @@ -190,7 +191,7 @@ describe('loginCommand', () => {
it('should login with a valid token in another region --region', async () => {
const mockToken = 'test-token'
const mockUser = { email: '[email protected]' }
loginWithToken.mockResolvedValue({ user: mockUser })
vi.mocked(loginWithToken).mockResolvedValue({ user: mockUser })

await loginCommand.parseAsync(['node', 'test', '--token', mockToken, '--region', 'us'])

Expand All @@ -204,7 +205,7 @@ describe('loginCommand', () => {
Please make sure you are using the correct token and try again.`)

loginWithToken.mockRejectedValue(mockError)
vi.mocked(loginWithToken).mockRejectedValue(mockError)

await loginCommand.parseAsync(['node', 'test', '--token', 'invalid-token'])

Expand All @@ -220,7 +221,7 @@ describe('loginCommand', () => {
expect(konsola.error).toHaveBeenCalledWith(expect.any(Error), true)

// Access the error argument
const errorArg = konsola.error.mock.calls[0][0]
const errorArg = vi.mocked(konsola.error).mock.calls[0][0]

// Build the expected error message
const expectedMessage = `The provided region: invalid-region is not valid. Please use one of the following values: ${Object.values(regions).join(' | ')}`
Expand Down
4 changes: 2 additions & 2 deletions src/commands/logout/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ describe('logoutCommand', () => {
})

it('should log out the user if has previously login', async () => {
isAuthorized.mockResolvedValue(true)
vi.mocked(isAuthorized).mockResolvedValue(true)

await logoutCommand.parseAsync(['node', 'test'])
expect(removeNetrcEntry).toHaveBeenCalled()
})

it('should not log out the user if has not previously login', async () => {
isAuthorized.mockResolvedValue(false)
vi.mocked(isAuthorized).mockResolvedValue(false)
await logoutCommand.parseAsync(['node', 'test'])
expect(removeNetrcEntry).not.toHaveBeenCalled()
})
Expand Down
2 changes: 1 addition & 1 deletion src/creds.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ describe('creds', async () => {
getNetrcCredentials: async () => {
return {
'api.storyblok.com': {
login: 'julio.iglesias@storyblok.co,m',
login: 'julio.iglesias@storyblok.com',
password: 'my_access',
region: 'eu',
},
Expand Down

0 comments on commit de2f3bb

Please sign in to comment.