|
| 1 | +/* SPDX-FileCopyrightText: 2025 Greenbone AG |
| 2 | + * |
| 3 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 4 | + */ |
| 5 | + |
| 6 | +import {showSuccessNotification} from '@greenbone/opensight-ui-components-mantinev7'; |
| 7 | +import {describe, test, expect, testing} from '@gsa/testing'; |
| 8 | +import actionFunction from 'web/entity/hooks/actionFunction'; |
| 9 | + |
| 10 | +vi.mock('@greenbone/opensight-ui-components-mantinev7', () => ({ |
| 11 | + showSuccessNotification: vi.fn(), |
| 12 | +})); |
| 13 | + |
| 14 | +describe('actionFunction', () => { |
| 15 | + beforeEach(() => { |
| 16 | + testing.resetAllMocks(); |
| 17 | + }); |
| 18 | + test('should call onSuccess with response and show success notification if successMessage is defined', async () => { |
| 19 | + const promise = Promise.resolve('response'); |
| 20 | + const onSuccess = testing.fn(); |
| 21 | + const onError = testing.fn(); |
| 22 | + const successMessage = 'Success!'; |
| 23 | + |
| 24 | + await actionFunction(promise, onSuccess, onError, successMessage); |
| 25 | + |
| 26 | + expect(onSuccess).toHaveBeenCalledWith('response'); |
| 27 | + expect(showSuccessNotification).toHaveBeenCalledWith(successMessage); |
| 28 | + }); |
| 29 | + |
| 30 | + test('should call onSuccess with response and not show success notification if successMessage is not defined', async () => { |
| 31 | + const promise = Promise.resolve('response'); |
| 32 | + const onSuccess = testing.fn(); |
| 33 | + const onError = testing.fn(); |
| 34 | + |
| 35 | + await actionFunction(promise, onSuccess, onError); |
| 36 | + |
| 37 | + expect(onSuccess).toHaveBeenCalledWith('response'); |
| 38 | + expect(showSuccessNotification).not.toHaveBeenCalled(); |
| 39 | + }); |
| 40 | + |
| 41 | + test('should call onError with error if promise rejects and onError is defined', async () => { |
| 42 | + const promise = Promise.reject('error'); |
| 43 | + const onSuccess = testing.fn(); |
| 44 | + const onError = testing.fn(); |
| 45 | + |
| 46 | + await actionFunction(promise, onSuccess, onError); |
| 47 | + |
| 48 | + expect(onError).toHaveBeenCalledWith('error'); |
| 49 | + }); |
| 50 | + |
| 51 | + test('should throw error if promise rejects and onError is not defined', async () => { |
| 52 | + const promise = Promise.reject('error'); |
| 53 | + const onSuccess = testing.fn(); |
| 54 | + const onError = undefined; |
| 55 | + |
| 56 | + await expect(actionFunction(promise, onSuccess, onError)).rejects.toEqual( |
| 57 | + 'error', |
| 58 | + ); |
| 59 | + }); |
| 60 | +}); |
0 commit comments