index.test.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. data: null,
  36. params: null,
  37. headers: {
  38. Authorization: `Bearer ${difyClient.apiKey}`,
  39. 'Content-Type': 'application/json',
  40. },
  41. responseType: 'json',
  42. })
  43. })
  44. it('should handle errors from the API', async () => {
  45. const method = 'GET'
  46. const endpoint = '/test-endpoint'
  47. const errorMessage = 'Request failed with status code 404'
  48. axios.mockRejectedValue(new Error(errorMessage))
  49. await expect(difyClient.sendRequest(method, endpoint)).rejects.toThrow(
  50. errorMessage
  51. )
  52. })
  53. })