-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.test.ts
More file actions
223 lines (188 loc) · 7.22 KB
/
index.test.ts
File metadata and controls
223 lines (188 loc) · 7.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MermaidChart } from './index.js';
import { AICreditsLimitExceededError } from './errors.js';
import type { AuthorizationData } from './types.js';
import { URLS } from './urls.js';
import { OAuth2Client } from '@badgateway/oauth2-client';
const mockOAuth2ClientRequest = (async (endpoint, _body) => {
switch (endpoint) {
case 'tokenEndpoint':
return {
access_token: 'test-example-access_token',
refresh_token: 'test-example-refresh_token',
token_type: 'Bearer',
expires_in: 3600,
};
default:
throw new Error('mock unimplemented');
}
}) as typeof OAuth2Client.prototype.request;
describe('MermaidChart', () => {
let client: MermaidChart;
beforeEach(() => {
vi.resetAllMocks();
vi.spyOn(OAuth2Client.prototype, 'request').mockImplementation(mockOAuth2ClientRequest);
client = new MermaidChart({
clientID: '00000000-0000-0000-0000-000000000dead',
baseURL: 'https://test.mermaidchart.invalid',
redirectURI: 'https://localhost.invalid',
});
vi.spyOn(client, 'getUser').mockImplementation(async () => {
return {
fullName: 'Test User',
emailAddress: 'test@invalid.invalid',
};
});
});
describe('#getAuthorizationData', () => {
it('should set default state', async () => {
const { state, url } = await client.getAuthorizationData();
expect(new URL(url).searchParams.has('state', state)).toBeTruthy();
});
});
describe('#handleAuthorizationResponse', () => {
let state: AuthorizationData['state'];
beforeEach(async () => {
({ state } = await client.getAuthorizationData({ state }));
});
it('should set token', async () => {
const code = 'hello-world';
await client.handleAuthorizationResponse(
`https://response.invalid?code=${code}&state=${state}`,
);
await expect(client.getAccessToken()).resolves.toBe('test-example-access_token');
});
it('should throw with invalid state', async () => {
await expect(() =>
client.handleAuthorizationResponse(
'https://response.invalid?code=hello-world&state=my-invalid-state',
),
).rejects.toThrowError('invalid_state');
});
it('should throw with nicer error if URL has no query params', async () => {
await expect(() =>
client.handleAuthorizationResponse(
// missing the ? so it's not read as a query
'code=hello-world&state=my-invalid-state',
),
).rejects.toThrowError(/no query parameters/);
});
it('should work in Node.JS with url fragment', async () => {
const code = 'hello-nodejs-world';
await client.handleAuthorizationResponse(`?code=${code}&state=${state}`);
await expect(client.getAccessToken()).resolves.toBe('test-example-access_token');
});
});
describe('#diagramChat', () => {
beforeEach(async () => {
await client.setAccessToken('test-access-token');
});
it('should parse JSON response with text and documentChatThreadID', async () => {
const jsonResponse = {
text: 'Hello, here is your diagram!',
documentChatThreadID: 'thread-abc-123',
documentID: 'doc-123',
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn((client as any).axios, 'post').mockResolvedValue({ data: jsonResponse });
const result = await client.diagramChat({
message: 'Create a flowchart',
documentID: 'doc-123',
});
expect(result.text).toBe('Hello, here is your diagram!');
expect(result.documentChatThreadID).toBe('thread-abc-123');
expect(result.documentID).toBe('doc-123');
});
it('should throw AICreditsLimitExceededError on 402', async () => {
// Mock the underlying axios call to simulate a 402 response from the API
// so the actual error-mapping logic inside diagramChat() is exercised.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn((client as any).axios, 'post').mockRejectedValue({
response: {
status: 402,
data: 'AI credits limit exceeded',
},
});
await expect(
client.diagramChat({
message: 'Create a flowchart',
documentID: 'doc-123',
}),
).rejects.toThrow(AICreditsLimitExceededError);
});
});
describe('#repairDiagram', () => {
beforeEach(async () => {
await client.setAccessToken('test-access-token');
});
it('should repair diagram successfully', async () => {
vi.spyOn(client, 'repairDiagram').mockResolvedValue({
result: 'ok' as const,
code: '```mermaid\ngraph TD\n A[Start] --> B[End]\n```',
solved: true,
});
const result = await client.repairDiagram({
code: 'graph TD\n A[Start] --> B{Decision}',
error: 'Syntax error',
});
expect(result.result).toBe('ok');
expect(result.solved).toBe(true);
});
it('should throw AICreditsLimitExceededError on 402', async () => {
// Mock the underlying axios call to simulate a 402 response from the API
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn((client as any).axios, 'post').mockRejectedValue({
response: {
status: 402,
data: 'AI credits limit exceeded',
},
});
await expect(
client.repairDiagram({
code: 'graph TD\n A --> B',
error: 'Syntax error',
}),
).rejects.toThrow(AICreditsLimitExceededError);
});
});
describe('#suggestPrSummary', () => {
beforeEach(async () => {
await client.setAccessToken('test-access-token');
});
it('should POST to the pr-summary endpoint with the request body and return response.data', async () => {
const jsonResponse = {
title: 'Add validation step to flowchart',
description: '## What changed\n- Added node C',
branchName: 'feature/flowchart-validation',
commitMessage: 'Add validation node C',
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const postSpy = vi.spyOn((client as any).axios, 'post').mockResolvedValue({
data: jsonResponse,
});
const requestBody = {
originalDiagram: 'flowchart TD\n A --> B',
editedDiagram: 'flowchart TD\n A --> B\n B --> C[Validate]',
};
const result = await client.suggestPrSummary(requestBody);
expect(postSpy).toHaveBeenCalledWith(URLS.rest.openai.prSummary, requestBody);
expect(result).toEqual(jsonResponse);
});
it('should throw AICreditsLimitExceededError on 402', async () => {
// Mock the underlying axios call so the error mapping in suggestPrSummary is exercised.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn((client as any).axios, 'post').mockRejectedValue({
response: {
status: 402,
data: 'AI credits limit exceeded',
},
});
await expect(
client.suggestPrSummary({
originalDiagram: 'flowchart TD\n A --> B',
editedDiagram: 'flowchart TD\n A --> B\n B --> C',
}),
).rejects.toThrow(AICreditsLimitExceededError);
});
});
});