import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CompanySearchResult } from '../src/api/assets'
import { Watchlist } from '../src/pages/Watchlist'
const { listAssets, searchCompanies, addAsset, removeAsset } = vi.hoisted(() => ({
listAssets: vi.fn(),
searchCompanies: vi.fn(),
addAsset: vi.fn(),
removeAsset: vi.fn(),
}))
vi.mock('@/api/assets', () => ({
assetsApi: {
list: listAssets,
search: searchCompanies,
searchCompanies,
add: addAsset,
remove: removeAsset,
},
}))
const historicalIndex = {
id: 'historical-index-19', user_id: 'user-19', symbol: 'SSAAPL INDEX',
name: 'Historic S&P index', figi: null, created_at: '2025-01-01T00:00:00.000Z',
}
const companyMatches = [
{ company_id: 'isin:CNE100001526', name: 'BYD Company Limited', exchange: 'Shenzhen Stock Exchange', country: 'China', mic: 'XSHE' },
{ company_id: 'isin:HK0285041858', name: 'BYD Electronic (International) Company Limited', exchange: 'Hong Kong Stock Exchange', country: 'China', mic: 'XHKG' },
] satisfies CompanySearchResult[]
describe('Ticket #19 — company-first watchlist search', () => {
afterEach(cleanup)
beforeEach(() => {
vi.clearAllMocks()
listAssets.mockResolvedValue([historicalIndex])
searchCompanies.mockResolvedValue(companyMatches)
addAsset.mockResolvedValue({ id: 'asset-company-byd', user_id: 'user-19', company_id: 'isin:CNE100001526' })
removeAsset.mockResolvedValue(undefined)
})
it('searches by company name, shows disambiguators without private tickers, and follows by company_id only while preserving history', async () => {
const user = userEvent.setup()
render()
const history = await screen.findByRole('region', { name: /actifs historiques/i })
expect(within(history).getByText('Historic S&P index')).toBeInTheDocument()
const query = await screen.findByRole('textbox', { name: /nom de l'entreprise/i })
expect(screen.getAllByRole('textbox')).toHaveLength(1)
await user.type(query, 'BYD')
expect(searchCompanies).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: /rechercher/i }))
await waitFor(() => expect(searchCompanies).toHaveBeenCalledWith('BYD', 20))
const results = await screen.findByRole('region', { name: /résultats des entreprises/i })
const byd = within(results).getByText('BYD Company Limited').closest('li')
expect(byd).not.toBeNull()
expect(within(byd!).getByText('Shenzhen Stock Exchange')).toBeInTheDocument()
expect(within(byd!).getByText('China')).toBeInTheDocument()
expect(within(results).getByText('BYD Electronic (International) Company Limited')).toBeInTheDocument()
for (const privateValue of ['002594.SZ', '0285.HK', 'BBG001QVK2K1', 'BBG000JPLTR7']) {
expect(within(results).queryByText(privateValue)).not.toBeInTheDocument()
}
await user.click(within(byd!).getByRole('button', { name: /suivre/i }))
await waitFor(() => expect(addAsset).toHaveBeenCalledWith({ company_id: 'isin:CNE100001526' }))
expect(addAsset).toHaveBeenCalledTimes(1)
expect(history).toHaveTextContent('Historic S&P index')
})
it('présente le nom officiel, le pays et la place boursière sans identifiant technique, et protège tous les anciens suivis', async () => {
listAssets.mockResolvedValueOnce([historicalIndex, { ...historicalIndex, id: 'index-with-figi', name: 'Existing index', figi: 'BBG-OLD' }])
searchCompanies.mockResolvedValueOnce([{ ...companyMatches[0], symbol: '002594.SZ', figi: 'BBG001QVK2K1' }])
const user = userEvent.setup()
render()
const history = await screen.findByRole('region', { name: /autres suivis existants/i })
expect(within(history).getByText('Existing index')).toBeInTheDocument()
expect(within(history).queryByRole('button')).not.toBeInTheDocument()
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'BYD{Enter}')
const results = await screen.findByRole('region', { name: /résultats des entreprises/i })
expect(await within(results).findByText('Shenzhen Stock Exchange')).toBeInTheDocument()
expect(within(results).getByText('China')).toBeInTheDocument()
expect(within(results).getByText('BYD Company Limited')).toHaveClass('font-semibold')
for (const value of ['002594.SZ', 'BBG001QVK2K1', 'isin:CNE100001526', 'XSHE']) expect(within(results).queryByText(value)).not.toBeInTheDocument()
expect(addAsset).not.toHaveBeenCalled()
expect(removeAsset).not.toHaveBeenCalled()
})
it('follows and undoes an unfollow in English using only company_id', async () => {
listAssets.mockResolvedValueOnce([{ id: 'byd-followed', company_id: companyMatches[0].company_id, name: companyMatches[0].name, symbol: '002594.SZ', figi: 'private-figi' }])
const user = userEvent.setup()
render()
await user.selectOptions(screen.getByLabelText('Langue / Language'), 'en')
await screen.findByText('BYD Company Limited')
expect(screen.getByLabelText('Company name')).toBeInTheDocument()
expect(screen.queryByText('002594.SZ')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Unfollow BYD Company Limited' }))
expect(await screen.findByText('Company unfollowed.')).toBeInTheDocument()
expect(removeAsset).toHaveBeenCalledWith('byd-followed')
await user.click(screen.getByRole('button', { name: 'Undo unfollow' }))
expect(await screen.findByText('Unfollow undone.')).toBeInTheDocument()
expect(addAsset).toHaveBeenCalledWith({ company_id: companyMatches[0].company_id })
expect(screen.getByText('BYD Company Limited')).toBeInTheDocument()
})
it('garde le nom recherché après erreur et permet une reprise explicite', async () => {
searchCompanies.mockRejectedValueOnce(new Error('offline'))
const user = userEvent.setup()
render()
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'BYD{Enter}')
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible de rechercher des entreprises')
expect(screen.getByLabelText("Nom de l'entreprise")).toHaveValue('BYD')
expect(searchCompanies).toHaveBeenCalledTimes(1)
await user.click(screen.getByRole('button', { name: 'Réessayer' }))
expect(await screen.findByText('BYD Company Limited')).toBeInTheDocument()
expect(searchCompanies).toHaveBeenCalledTimes(2)
})
it('désambiguïse deux noms identiques avec pays et place sans afficher le MIC', async () => {
searchCompanies.mockResolvedValueOnce([
{ company_id: 'company-us', name: 'Example Company', country: 'United States', exchange: 'Nasdaq', mic: 'XNAS' },
{ company_id: 'company-uk', name: 'Example Company', country: 'United Kingdom', exchange: 'London Stock Exchange', mic: 'XLON' },
] satisfies CompanySearchResult[])
const user = userEvent.setup()
render()
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'Example{Enter}')
const results = screen.getByRole('region', { name: /résultats des entreprises/i })
const names = await within(results).findAllByText('Example Company')
expect(names).toHaveLength(2)
const us = names[0].closest('li')!
const uk = names[1].closest('li')!
expect(within(us).getByText('United States')).toBeInTheDocument()
expect(within(us).getByText('Nasdaq')).toBeInTheDocument()
expect(within(uk).getByText('United Kingdom')).toBeInTheDocument()
expect(within(uk).getByText('London Stock Exchange')).toBeInTheDocument()
expect(within(results).queryByText(/XNAS|XLON|company-us|company-uk/)).not.toBeInTheDocument()
await user.click(within(uk).getByRole('button', { name: /suivre/i }))
expect(addAsset).toHaveBeenCalledWith({ company_id: 'company-uk' })
})
it('affiche uniquement le nom si pays et place ne sont pas renseignés', async () => {
searchCompanies.mockResolvedValueOnce([{ company_id: 'company-unknown', name: 'Example Company', country: '', exchange: '', mic: 'XNAS' }] satisfies CompanySearchResult[])
const user = userEvent.setup()
render()
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'Example{Enter}')
const name = await screen.findByText('Example Company')
expect(name).toHaveClass('font-semibold')
expect(screen.queryByText('XNAS')).not.toBeInTheDocument()
expect(screen.queryByText('undefined')).not.toBeInTheDocument()
})
})