index.test.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { DifyClient, BASE_URL, routes } from ".";
  2. import axios from 'axios'
  3. jest.mock('axios')
  4. describe('Client', () => {
  5. let difyClient
  6. beforeEach(() => {
  7. difyClient = new DifyClient('test')
  8. })
  9. test('should create a client', () => {
  10. expect(difyClient).toBeDefined();
  11. })
  12. // test updateApiKey
  13. test('should update the api key', () => {
  14. difyClient.updateApiKey('test2');
  15. expect(difyClient.apiKey).toBe('test2');
  16. })
  17. });
  18. describe('Send Requests', () => {
  19. let difyClient
  20. beforeEach(() => {
  21. difyClient = new DifyClient('test')
  22. })
  23. afterEach(() => {
  24. jest.resetAllMocks()
  25. })
  26. it('should make a successful request to the application parameter', async () => {
  27. const method = 'GET'
  28. const endpoint = routes.application.url
  29. const expectedResponse = { data: 'response' }
  30. axios.mockResolvedValue(expectedResponse)
  31. await difyClient.sendRequest(method, endpoint)
  32. expect(axios).toHaveBeenCalledWith({
  33. method,
  34. url: `${BASE_URL}${endpoint}`,
  35. params: null,
  36. headers: {
  37. Authorization: `Bearer ${difyClient.apiKey}`,
  38. 'Content-Type': 'application/json',
  39. },
  40. responseType: 'json',
  41. })
  42. })
  43. it('should handle errors from the API', async () => {
  44. const method = 'GET'
  45. const endpoint = '/test-endpoint'
  46. const errorMessage = 'Request failed with status code 404'
  47. axios.mockRejectedValue(new Error(errorMessage))
  48. await expect(difyClient.sendRequest(method, endpoint)).rejects.toThrow(
  49. errorMessage
  50. )
  51. })
  52. })