From 7d00e0e747fc9e045154836ce0fe1677563b3886 Mon Sep 17 00:00:00 2001 From: crazywoola <427733928@qq.com> Date: Mon, 15 May 2023 19:40:45 +0800 Subject: [PATCH] feat: add test --- sdks/nodejs-client/index.test.js | 66 ++++++++++++++++++++++++++++++++ sdks/nodejs-client/package.json | 3 ++ 2 files changed, 69 insertions(+) create mode 100644 sdks/nodejs-client/index.test.js diff --git a/sdks/nodejs-client/index.test.js b/sdks/nodejs-client/index.test.js new file mode 100644 index 0000000000..e08b8e82af --- /dev/null +++ b/sdks/nodejs-client/index.test.js @@ -0,0 +1,66 @@ +import { DifyClient, BASE_URL, routes } from "."; + +import axios from 'axios' + +jest.mock('axios') + +describe('Client', () => { + let difyClient + beforeEach(() => { + difyClient = new DifyClient('test') + }) + + test('should create a client', () => { + expect(difyClient).toBeDefined(); + }) + // test updateApiKey + test('should update the api key', () => { + difyClient.updateApiKey('test2'); + expect(difyClient.apiKey).toBe('test2'); + }) +}); + +describe('Send Requests', () => { + let difyClient + + beforeEach(() => { + difyClient = new DifyClient('test') + }) + + afterEach(() => { + jest.resetAllMocks() + }) + + it('should make a successful request to the application parameter', async () => { + const method = 'GET' + const endpoint = routes.application.url + const expectedResponse = { data: 'response' } + axios.mockResolvedValue(expectedResponse) + + await difyClient.sendRequest(method, endpoint) + + expect(axios).toHaveBeenCalledWith({ + method, + url: `${BASE_URL}${endpoint}`, + data: null, + params: null, + headers: { + Authorization: `Bearer ${difyClient.apiKey}`, + 'Content-Type': 'application/json', + }, + responseType: 'json', + }) + + }) + + it('should handle errors from the API', async () => { + const method = 'GET' + const endpoint = '/test-endpoint' + const errorMessage = 'Request failed with status code 404' + axios.mockRejectedValue(new Error(errorMessage)) + + await expect(difyClient.sendRequest(method, endpoint)).rejects.toThrow( + errorMessage + ) + }) +}) \ No newline at end of file diff --git a/sdks/nodejs-client/package.json b/sdks/nodejs-client/package.json index 9c1a5ed5cf..069fe791f3 100644 --- a/sdks/nodejs-client/package.json +++ b/sdks/nodejs-client/package.json @@ -14,6 +14,9 @@ " <<427733928@qq.com>> (https://github.com/crazywoola)" ], "license": "MIT", + "scripts": { + "test": "next dev" + }, "dependencies": { "axios": "^1.3.5" }