/ clis / sinafinance / stock.test.js
stock.test.js
 1  import { beforeEach, describe, expect, it, vi } from 'vitest';
 2  import { getRegistry } from '@jackwener/opencli/registry';
 3  import './stock.js';
 4  
 5  function textResponse(body) {
 6      return {
 7          ok: true,
 8          arrayBuffer: async () => Buffer.from(body, 'utf8'),
 9      };
10  }
11  
12  describe('sinafinance stock command', () => {
13      beforeEach(() => {
14          vi.restoreAllMocks();
15          vi.stubGlobal('TextDecoder', class {
16              decode(buf) {
17                  return Buffer.from(buf).toString('utf8');
18              }
19          });
20      });
21  
22      it('prefers exact symbol match over partial symbol and name misses', async () => {
23          const cmd = getRegistry().get('sinafinance/stock');
24          expect(cmd?.func).toBeTypeOf('function');
25  
26          const fetchMock = vi.fn()
27              .mockResolvedValueOnce(textResponse('var suggestvalue="x,41,,AAPL,苹果;x,41,,AAPLU,Apple Units";'))
28              .mockResolvedValueOnce(textResponse('var hq_str_gb_AAPL="Apple Inc,189.98,1.23,0,1.56,0,188.50,180.00,195.00,175.00,1200000,0,3000000000000";'));
29          vi.stubGlobal('fetch', fetchMock);
30  
31          const result = await cmd.func(null, { key: 'AAPL', market: 'auto' });
32  
33          expect(fetchMock).toHaveBeenNthCalledWith(1, 'https://suggest3.sinajs.cn/suggest/type=11,31,41&key=AAPL', expect.any(Object));
34          expect(fetchMock).toHaveBeenNthCalledWith(2, 'https://hq.sinajs.cn/list=gb_AAPL', expect.any(Object));
35          expect(result[0]).toMatchObject({
36              Symbol: 'AAPL',
37              Name: 'Apple Inc',
38              Price: '189.98',
39          });
40      });
41  
42      it('still matches by display name when the query targets the company name', async () => {
43          const cmd = getRegistry().get('sinafinance/stock');
44          expect(cmd?.func).toBeTypeOf('function');
45  
46          const fetchMock = vi.fn()
47              .mockResolvedValueOnce(textResponse('var suggestvalue="x,41,,AAPL,苹果;x,41,,AAPLU,Apple Units";'))
48              .mockResolvedValueOnce(textResponse('var hq_str_gb_AAPL="苹果公司,189.98,1.23,0,1.56,0,188.50,180.00,195.00,175.00,1200000,0,3000000000000";'));
49          vi.stubGlobal('fetch', fetchMock);
50  
51          const result = await cmd.func(null, { key: '苹果', market: 'auto' });
52  
53          expect(fetchMock).toHaveBeenNthCalledWith(2, 'https://hq.sinajs.cn/list=gb_AAPL', expect.any(Object));
54          expect(result[0]).toMatchObject({
55              Symbol: 'AAPL',
56              Name: '苹果公司',
57          });
58      });
59  });