import { http, HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import { getUserInfoHandler } from '../src/tools/example.tool.js'
import { server } from './mocks/server'
describe('getUserInfoHandler', () => {
it('should return user data on successful fetch', async () => {
server.use(
http.get('https://api.example.com/users/1', () => {
return HttpResponse.json({ id: '1', name: 'John Doe' })
}),
)
// We need to mock the fetch call inside the handler
globalThis.fetch = async (url) => {
if (url === 'https://api.example.com/users/1') {
return new Response(JSON.stringify({ id: '1', name: 'John Doe' }), {
status: 200,
})
}
return new Response(null, { status: 404 })
}
const result = await getUserInfoHandler({ userId: '1' })
expect(result.isError).toBeFalsy()
expect(result.content[0].text).toEqual(
JSON.stringify({ id: '1', name: 'John Doe' }),
)
})
it('should return an error on failed fetch', async () => {
server.use(
http.get('https://api.example.com/users/2', () => {
return new HttpResponse(null, { status: 404 })
}),
)
globalThis.fetch = async (_url) => {
return new Response(null, { status: 404 })
}
const result = await getUserInfoHandler({ userId: '2' })
expect(result.isError).toBe(true)
expect(result.content[0].text).toEqual('User not found')
})
})