Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

feedback.test.ts 6.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. import readline from 'readline';
  2. // Import *after* mocking
  3. import { sendFeedback, gatherFeedback } from '../src/feedback';
  4. import { fetchWithProxy } from '../src/fetch';
  5. import logger from '../src/logger';
  6. // Store the original implementation to reference in mocks
  7. const actualFeedback = jest.requireActual('../src/feedback');
  8. // Mock dependencies
  9. jest.mock('../src/fetch', () => ({
  10. fetchWithProxy: jest.fn(),
  11. }));
  12. jest.mock('../src/logger', () => ({
  13. info: jest.fn(),
  14. error: jest.fn(),
  15. }));
  16. jest.mock('../src/globalConfig/accounts', () => ({
  17. getUserEmail: jest.fn(),
  18. }));
  19. // Create a type for our mocked question function
  20. type MockQuestionFn = jest.Mock<void, [string, (answer: string) => void]>;
  21. // Create a partial readline Interface mock
  22. const createMockInterface = () => {
  23. return {
  24. question: jest.fn((query: string, callback: (answer: string) => void) => {
  25. callback('mocked answer');
  26. }) as MockQuestionFn,
  27. close: jest.fn(),
  28. on: jest.fn(),
  29. // Add minimum required properties to satisfy the Interface type
  30. line: '',
  31. cursor: 0,
  32. setPrompt: jest.fn(),
  33. getPrompt: jest.fn(),
  34. write: jest.fn(),
  35. pause: jest.fn(),
  36. resume: jest.fn(),
  37. clearLine: jest.fn(),
  38. removeAllListeners: jest.fn(),
  39. terminal: null,
  40. input: { on: jest.fn() } as any,
  41. output: { on: jest.fn() } as any,
  42. } as unknown as readline.Interface;
  43. };
  44. jest.mock('readline', () => ({
  45. createInterface: jest.fn(() => createMockInterface()),
  46. }));
  47. // Mock feedback module
  48. jest.mock('../src/feedback', () => {
  49. return {
  50. sendFeedback: jest.fn(),
  51. gatherFeedback: jest.fn(),
  52. };
  53. });
  54. // Helper to create a mock Response
  55. const createMockResponse = (data: any): Response => {
  56. return {
  57. ok: data.ok,
  58. status: data.status || 200,
  59. statusText: data.statusText || '',
  60. headers: new Headers(),
  61. redirected: false,
  62. type: 'basic',
  63. url: '',
  64. json: async () => data,
  65. text: async () => '',
  66. arrayBuffer: async () => new ArrayBuffer(0),
  67. blob: async () => new Blob(),
  68. formData: async () => new FormData(),
  69. bodyUsed: false,
  70. body: null,
  71. clone: () => createMockResponse(data),
  72. } as Response;
  73. };
  74. describe('Feedback Module', () => {
  75. // Store original console.log
  76. const originalConsoleLog = console.log;
  77. beforeEach(() => {
  78. // Reset all mocks before each test
  79. jest.clearAllMocks();
  80. // Silence console output during tests
  81. jest.spyOn(console, 'log').mockImplementation();
  82. });
  83. afterEach(() => {
  84. // Restore console.log after each test
  85. console.log = originalConsoleLog;
  86. });
  87. describe('sendFeedback', () => {
  88. // Add the actual implementation for these tests
  89. beforeEach(() => {
  90. jest.mocked(sendFeedback).mockImplementation(actualFeedback.sendFeedback);
  91. });
  92. it('should send feedback successfully', async () => {
  93. // Mock a successful API response
  94. const mockResponse = createMockResponse({ ok: true });
  95. jest.mocked(fetchWithProxy).mockResolvedValueOnce(mockResponse);
  96. await sendFeedback('Test feedback');
  97. // Verify fetch was called with correct parameters
  98. expect(fetchWithProxy).toHaveBeenCalledWith(
  99. 'https://api.promptfoo.dev/api/feedback',
  100. expect.objectContaining({
  101. method: 'POST',
  102. headers: { 'Content-Type': 'application/json' },
  103. body: JSON.stringify({ message: 'Test feedback' }),
  104. }),
  105. );
  106. // Verify success message was logged
  107. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Feedback sent'));
  108. });
  109. it('should handle API failure', async () => {
  110. // Mock a failed API response
  111. const mockResponse = createMockResponse({ ok: false, status: 500 });
  112. jest.mocked(fetchWithProxy).mockResolvedValueOnce(mockResponse);
  113. await sendFeedback('Test feedback');
  114. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Failed to send feedback'));
  115. });
  116. it('should handle network errors', async () => {
  117. // Mock a network error
  118. jest.mocked(fetchWithProxy).mockRejectedValueOnce(new Error('Network error'));
  119. await sendFeedback('Test feedback');
  120. expect(logger.error).toHaveBeenCalledWith('Network error while sending feedback');
  121. });
  122. it('should not send empty feedback', async () => {
  123. await sendFeedback('');
  124. // Verify that fetch was not called
  125. expect(fetchWithProxy).not.toHaveBeenCalled();
  126. });
  127. });
  128. describe('gatherFeedback', () => {
  129. it('should send feedback directly if a message is provided', async () => {
  130. // Create a simplified implementation for this test
  131. jest.mocked(gatherFeedback).mockImplementation(async (message) => {
  132. if (message) {
  133. await sendFeedback(message);
  134. }
  135. });
  136. // Reset sendFeedback to be a jest function we can track
  137. jest.mocked(sendFeedback).mockReset();
  138. // Run the test
  139. await gatherFeedback('Direct feedback');
  140. // Verify sendFeedback was called with the direct message
  141. expect(sendFeedback).toHaveBeenCalledWith('Direct feedback');
  142. });
  143. it('should handle empty feedback input', async () => {
  144. // Setup readline to return empty feedback
  145. const mockInterface = createMockInterface();
  146. // Override the default behavior for this test
  147. (mockInterface.question as MockQuestionFn).mockImplementationOnce(
  148. (_: string, callback: (answer: string) => void) => callback(' '),
  149. );
  150. jest.mocked(readline.createInterface).mockReturnValue(mockInterface);
  151. // Use real implementation for gatherFeedback
  152. jest.mocked(gatherFeedback).mockImplementation(actualFeedback.gatherFeedback);
  153. await gatherFeedback();
  154. // Verify sendFeedback was not called due to empty input
  155. expect(sendFeedback).not.toHaveBeenCalled();
  156. });
  157. it('should handle errors during feedback gathering', async () => {
  158. // Mock readline to throw an error
  159. jest.mocked(readline.createInterface).mockImplementation(() => {
  160. throw new Error('Test error');
  161. });
  162. // Use real implementation for gatherFeedback
  163. jest.mocked(gatherFeedback).mockImplementation(actualFeedback.gatherFeedback);
  164. await gatherFeedback();
  165. expect(logger.error).toHaveBeenCalledWith(
  166. expect.stringContaining('Error gathering feedback'),
  167. );
  168. });
  169. });
  170. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...