Skip to content

Commit

Permalink
feat: remove sideeffects from pull languages actions and test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Oct 31, 2024
1 parent 8cdc543 commit f7cbd35
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 13 deletions.
93 changes: 93 additions & 0 deletions src/commands/pull-languages/actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import chalk from 'chalk'

Check failure on line 3 in src/commands/pull-languages/actions.test.ts

View workflow job for this annotation

GitHub Actions / Lint (20)

'chalk' is defined but never used
import { vol } from 'memfs'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { pullLanguages, saveLanguagesToFile } from './actions'

const handlers = [
http.get('https://api.storyblok.com/v1/spaces/12345', async ({ request }) => {
const token = request.headers.get('Authorization')
if (token === 'valid-token') {
return HttpResponse.json({
space: {
default_lang_name: 'en',
languages: [
{
code: 'ca',
name: 'Catalan',
},
{
code: 'fr',
name: 'French',
},
],
},
})
}
return new HttpResponse('Unauthorized', { status: 401 })
}),
]

const server = setupServer(...handlers)

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))

afterEach(() => server.resetHandlers())
afterAll(() => server.close())

vi.mock('node:fs')
vi.mock('node:fs/promises')

describe('pull languages actions', () => {
beforeEach(() => {
vi.clearAllMocks()
vol.reset()
})

describe('pullLanguages', () => {
it('should pull languages successfully with a valid token', async () => {
const mockResponse = {
default_lang_name: 'en',
languages: [
{
code: 'ca',
name: 'Catalan',
},
{
code: 'fr',
name: 'French',
},
],
}
const result = await pullLanguages('12345', 'valid-token', 'eu')
expect(result).toEqual(mockResponse)
})
})
it('should throw an masked error for invalid token', async () => {
await expect(pullLanguages('12345', 'invalid-token', 'eu')).rejects.toThrow(
new Error(`The user is not authorized to access the API`),
)
})

describe('saveLanguagesToFile', () => {
it('should save languages to a json file with space number', async () => {
const mockResponse = {
default_lang_name: 'en',
languages: [
{
code: 'ca',
name: 'Catalan',
},
{
code: 'fr',
name: 'French',
},
],
}
await saveLanguagesToFile('12345', mockResponse, '/temp')
const content = vol.readFileSync('/temp/languages.12345.json', 'utf8')
expect(content).toBe(JSON.stringify(mockResponse, null, 2))
})
})
})
14 changes: 3 additions & 11 deletions src/commands/pull-languages/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { join, resolve } from 'node:path'
import { handleAPIError, handleFileSystemError } from '../../utils'
import { ofetch } from 'ofetch'
import { regionsDomain } from '../../constants'
import { session } from '../../session'
import { apiClient } from '../../api'

export interface SpaceInternationalizationOptions {
languages: SpaceLanguage[]
Expand All @@ -16,17 +14,11 @@ export interface SpaceLanguage {
name: string
}

export const pullLanguages = async (space: string): Promise<SpaceInternationalizationOptions | undefined> => {
export const pullLanguages = async (space: string, token: string, region: string): Promise<SpaceInternationalizationOptions | undefined> => {
try {
const { client } = apiClient()
if (!client) {
throw new Error('Client not initialized')
}

const { state } = session()
const response = await ofetch(`https://${regionsDomain[state.region]}/v1/spaces/${space}`, {
const response = await ofetch(`https://${regionsDomain[region]}/v1/spaces/${space}`, {
headers: {
Authorization: state.password,
Authorization: token,
},
})
return {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/pull-languages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const pullLanguagesCommand = program
const { state, initializeSession } = session()
await initializeSession()

if (!state.isLoggedIn) {
if (!state.isLoggedIn || !state.password || !state.region) {
handleError(new CommandError(`You are currently not logged in. Please login first to get your user info.`), verbose)
return
}
Expand All @@ -33,7 +33,7 @@ export const pullLanguagesCommand = program
}

try {
const internationalization = await pullLanguages(space)
const internationalization = await pullLanguages(space, state.password, state.region)

if (!internationalization || !internationalization.languages) {
konsola.warn(`No languages found in the space ${space}`)
Expand Down

0 comments on commit f7cbd35

Please sign in to comment.