feat: add test

This commit is contained in:
crazywoola 2023-05-15 19:40:45 +08:00
parent 0eca93ebd1
commit 7d00e0e747
2 changed files with 69 additions and 0 deletions

View File

@ -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
)
})
})

View File

@ -14,6 +14,9 @@
"<crazywoola> <<427733928@qq.com>> (https://github.com/crazywoola)"
],
"license": "MIT",
"scripts": {
"test": "next dev"
},
"dependencies": {
"axios": "^1.3.5"
}