var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { getSavedSearches, updateSavedSearch, deleteSavedSearch, getTotalsForQuery, createSavedSearch } from '@reltio/mdm-sdk';
import { showDefaultErrorMessage } from '../../helpers/errors';
import { PageRequestsAbortingContext } from '../../contexts/PageRequestsAbortingContext';
import { RequestStates } from '../../types';
import { useSavedSearchesRequest } from '../useSavedSearchesRequest';
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { getSavedSearches: jest.fn(), getTotalsForQuery: jest.fn(), createSavedSearch: jest.fn(), updateSavedSearch: jest.fn(), deleteSavedSearch: jest.fn() })); });
jest.mock('../../helpers/errors', function () { return (__assign(__assign({}, jest.requireActual('../../helpers/errors')), { showDefaultErrorMessage: jest.fn() })); });
var defaultProps = {
    options: { favoriteOnly: true, countResults: false },
    defaultRowsPerPage: 25
};
var signal = new AbortController().signal;
var setUp = function (props) {
    if (props === void 0) { props = defaultProps; }
    var Providers = function (_a) {
        var children = _a.children;
        return (React.createElement(PageRequestsAbortingContext.Provider, { value: signal }, children));
    };
    return renderHook(useSavedSearchesRequest, { wrapper: Providers, initialProps: props });
};
describe('useSavedSearchesRequest behavior', function () {
    var defaultSavedSearchesResponse = {
        favoriteOnly: true,
        max: 10,
        offset: 0,
        sortBy: 'NAME',
        sortOrder: 'ASC',
        total: 3,
        result: [
            {
                name: 'Crazy-mini',
                uri: 'avedSearch/1',
                query: encodeURIComponent("savedSearch1 range(activeness.startDate,'${lastDay}','${now}')")
            },
            {
                name: 'crazySS',
                uri: 'savedSearch/2',
                query: encodeURIComponent("savedSearch2 equals(type,'configuration/entityTypes/People')")
            },
            { name: 'wrong', uri: 'savedSearch/3', query: encodeURIComponent('wrong query') }
        ]
    };
    var resolveGetSavedSearches, rejectGetSavedSearches;
    beforeEach(function () {
        getSavedSearches.mockImplementation(function () {
            return new Promise(function (resolve, reject) {
                resolveGetSavedSearches = function (response) { return resolve(response); };
                rejectGetSavedSearches = reject;
            });
        });
        getTotalsForQuery.mockImplementation(function (query, heavySearchCircuitBreaker) {
            if (query.includes('savedSearch1')) {
                return Promise.resolve({ total: 1 });
            }
            if (query.includes('savedSearch2')) {
                return Promise.resolve({ total: heavySearchCircuitBreaker ? -1 : 2 });
            }
            return Promise.reject('Error from total');
        });
    });
    afterEach(function () {
        jest.restoreAllMocks();
        jest.clearAllMocks();
    });
    it('should send request and be in the loading state, and be in loaded state once data is loaded', function () { return __awaiter(void 0, void 0, void 0, function () {
        var hookResponse, result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    hookResponse = __assign(__assign({}, defaultSavedSearchesResponse), { result: [
                            { name: 'Crazy-mini', uri: 'savedSavedSearch/1' },
                            { name: 'crazySS', count: 18900000, uri: 'savedSearch/2' }
                        ] });
                    result = setUp().result;
                    expect(result.current.states.loading).toBe('loading');
                    return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                resolveGetSavedSearches(hookResponse);
                                return [2 /*return*/];
                            });
                        }); })];
                case 1:
                    _a.sent();
                    expect(result.current.states.loading).toBe('loaded');
                    expect(result.current.data).toStrictEqual(hookResponse.result);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not update state in case of cancel request', function () { return __awaiter(void 0, void 0, void 0, function () {
        var result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    result = setUp().result;
                    expect(result.current.states.loading).toBe('loading');
                    return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                rejectGetSavedSearches({ errorMessage: 'Error!!!', name: 'AbortError' });
                                return [2 /*return*/];
                            });
                        }); })];
                case 1:
                    _a.sent();
                    expect(result.current.states.loading).toBe('loading');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should send total requests if option countResults is true', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { options: __assign(__assign({}, defaultProps.options), { countResults: true }) });
                    result = setUp(props).result;
                    expect(result.current.states.loading).toBe('loading');
                    return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                resolveGetSavedSearches(defaultSavedSearchesResponse);
                                return [2 /*return*/];
                            });
                        }); })];
                case 1:
                    _a.sent();
                    expect(result.current.data).toStrictEqual([
                        __assign(__assign({}, defaultSavedSearchesResponse.result[0]), { count: 1 }),
                        __assign(__assign({}, defaultSavedSearchesResponse.result[1]), { count: 2 }),
                        defaultSavedSearchesResponse.result[2]
                    ]);
                    expect(result.current.states.loading).toBe('loaded');
                    expect(getTotalsForQuery.mock.calls.length).toBe(3);
                    expect(getTotalsForQuery.mock.calls[0][2]).toBe(signal);
                    expect(getTotalsForQuery.mock.calls[0][0]).not.toContain('lastDay');
                    expect(getTotalsForQuery.mock.calls[0][0]).not.toContain('now');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not fail with nil options', function () { return __awaiter(void 0, void 0, void 0, function () {
        var result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    result = setUp({ defaultRowsPerPage: 25 }).result;
                    expect(result.current.states.loading).toBe('loading');
                    return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                resolveGetSavedSearches(defaultSavedSearchesResponse);
                                return [2 /*return*/];
                            });
                        }); })];
                case 1:
                    _a.sent();
                    expect(result.current.states.loading).toBe('loaded');
                    expect(result.current.data).toStrictEqual(defaultSavedSearchesResponse.result);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not fail when response.result is undefined', function () { return __awaiter(void 0, void 0, void 0, function () {
        var result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    result = setUp().result;
                    return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                resolveGetSavedSearches(__assign(__assign({}, defaultSavedSearchesResponse), { result: undefined }));
                                return [2 /*return*/];
                            });
                        }); })];
                case 1:
                    _a.sent();
                    expect(result.current.states.loading).toBe('loaded');
                    expect(result.current.data).toStrictEqual([]);
                    return [2 /*return*/];
            }
        });
    }); });
    describe('Lazy saved search behaviour', function () {
        var defaultProps = {
            options: { favoriteOnly: true, countResults: true },
            queryEstimatorEnabled: true,
            defaultRowsPerPage: 25
        };
        it('should use heavySearchCircuitBreaker and get total -1 for heavy search', function () { return __awaiter(void 0, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp(defaultProps).result;
                        expect(result.current.states.loading).toBe('loading');
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        expect(result.current.states.loading).toBe('loaded');
                        expect(result.current.data).toStrictEqual([
                            __assign(__assign({}, defaultSavedSearchesResponse.result[0]), { count: 1 }),
                            __assign(__assign({}, defaultSavedSearchesResponse.result[1]), { count: -1 }),
                            defaultSavedSearchesResponse.result[2]
                        ]);
                        expect(getTotalsForQuery).toHaveBeenCalledTimes(3);
                        expect(getTotalsForQuery.mock.calls[0][2]).toBe(signal);
                        expect(getTotalsForQuery.mock.calls[0][0]).not.toContain('lastDay');
                        expect(getTotalsForQuery.mock.calls[0][0]).not.toContain('now');
                        return [2 /*return*/];
                }
            });
        }); });
        it('should load total by loadTotalForSearchByUri for heavy search', function () { return __awaiter(void 0, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp(defaultProps).result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        expect(result.current.data).toStrictEqual([
                            __assign(__assign({}, defaultSavedSearchesResponse.result[0]), { count: 1 }),
                            __assign(__assign({}, defaultSavedSearchesResponse.result[1]), { count: -1 }),
                            defaultSavedSearchesResponse.result[2]
                        ]);
                        expect(getTotalsForQuery).toHaveBeenCalledTimes(3);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    result.current.loadTotalForSearchByUri(defaultSavedSearchesResponse.result[1].uri);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(result.current.data).toStrictEqual([
                            __assign(__assign({}, defaultSavedSearchesResponse.result[0]), { count: 1 }),
                            __assign(__assign({}, defaultSavedSearchesResponse.result[1]), { count: 2, isLoadingTotal: false }),
                            defaultSavedSearchesResponse.result[2]
                        ]);
                        expect(getTotalsForQuery).toHaveBeenCalledTimes(4);
                        return [2 /*return*/];
                }
            });
        }); });
    });
    describe('createSearch tests', function () {
        var resolveCreateSavedSearch, rejectCreateSavedSearch;
        var createdSearch = {
            name: 'updated name',
            description: 'updated description',
            isPublic: false,
            query: encodeURIComponent("equals(type,'configuration/entityTypes/People')"),
            uiState: { version: '2.0' }
        };
        beforeEach(function () {
            createSavedSearch.mockImplementation(function () {
                return new Promise(function (resolve, reject) {
                    resolveCreateSavedSearch = resolve;
                    rejectCreateSavedSearch = reject;
                });
            });
        });
        it('should create search and reload saved searches correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
            var createSearchPromiseResult, result, createSearchResult, savedSearchesResponse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        getSavedSearches.mockClear();
                        expect(result.current.states.creating).toBe(RequestStates.INIT);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    createSearchPromiseResult = result.current.createSearch(createdSearch);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(createSavedSearch).toHaveBeenCalledWith([createdSearch]);
                        expect(result.current.states.creating).toBe(RequestStates.LOADING);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, resolveCreateSavedSearch(createdSearch)];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, createSearchPromiseResult];
                    case 4:
                        createSearchResult = _a.sent();
                        expect(createSearchResult).toEqual({ success: true, result: createdSearch });
                        expect(result.current.states.creating).toBe(RequestStates.LOADED);
                        expect(getSavedSearches).toHaveBeenCalledWith({ favoriteOnly: true, max: 25, offset: 0 }, signal);
                        expect(result.current.states.loading).toBe(RequestStates.LOADING);
                        savedSearchesResponse = __assign(__assign({}, defaultSavedSearchesResponse), { result: __spreadArray(__spreadArray([], defaultSavedSearchesResponse.result, true), [__assign(__assign({}, createdSearch), { uri: 'savedSearch/4' })], false) });
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(savedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 5:
                        _a.sent();
                        expect(result.current.states.loading).toBe(RequestStates.LOADED);
                        expect(result.current.data).toEqual(savedSearchesResponse.result);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should create search, go to the first page and reload saved searches correctly in case of page is not 0', function () { return __awaiter(void 0, void 0, void 0, function () {
            var result, savedSearchesResponse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        getSavedSearches.mockClear();
                        act(function () {
                            result.current.updatePage(1);
                        });
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(getSavedSearches).toHaveBeenCalledWith({ favoriteOnly: true, max: 25, offset: 25 }, signal);
                        getSavedSearches.mockClear();
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    result.current.createSearch(createdSearch);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, resolveCreateSavedSearch(createdSearch)];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 4:
                        _a.sent();
                        expect(getSavedSearches).toHaveBeenCalledWith({ favoriteOnly: true, max: 25, offset: 0 }, signal);
                        savedSearchesResponse = __assign(__assign({}, defaultSavedSearchesResponse), { result: __spreadArray(__spreadArray([], defaultSavedSearchesResponse.result, true), [__assign(__assign({}, createdSearch), { uri: 'savedSearch/4' })], false) });
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(savedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 5:
                        _a.sent();
                        expect(result.current.data).toEqual(savedSearchesResponse.result);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should show error message and should not reload saved searches in case of createSavedSearch rejects error', function () { return __awaiter(void 0, void 0, void 0, function () {
            var createSearchPromiseResult, result, createSearchResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        getSavedSearches.mockClear();
                        expect(result.current.states.creating).toBe(RequestStates.INIT);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    createSearchPromiseResult = result.current.createSearch(createdSearch);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(createSavedSearch).toHaveBeenCalledWith([createdSearch]);
                        expect(result.current.states.creating).toBe(RequestStates.LOADING);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, rejectCreateSavedSearch({ errorMessage: 'Something went wrong' })];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, createSearchPromiseResult];
                    case 4:
                        createSearchResult = _a.sent();
                        expect(createSearchResult).toEqual({ success: false, error: { errorMessage: 'Something went wrong' } });
                        expect(result.current.states.creating).toBe(RequestStates.ERROR);
                        expect(result.current.data).toEqual(defaultSavedSearchesResponse.result);
                        expect(getSavedSearches).not.toHaveBeenCalled();
                        expect(showDefaultErrorMessage).toHaveBeenCalledWith({ errorMessage: 'Something went wrong' });
                        return [2 /*return*/];
                }
            });
        }); });
    });
    describe('updateSearch tests', function () {
        var resolveUpdateSavedSearch, rejectUpdateSavedSearch;
        var updatedSearch = __assign(__assign({}, defaultSavedSearchesResponse.result[1]), { name: 'updated name', description: 'updated description' });
        beforeEach(function () {
            updateSavedSearch.mockImplementation(function () {
                return new Promise(function (resolve, reject) {
                    resolveUpdateSavedSearch = resolve;
                    rejectUpdateSavedSearch = reject;
                });
            });
        });
        it('should update search correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
            var updateSearchPromiseResult, result, updateSearchResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        expect(result.current.states.updating).toBe(RequestStates.INIT);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    updateSearchPromiseResult = result.current.updateSearch(updatedSearch);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(result.current.states.updating).toBe(RequestStates.LOADING);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, resolveUpdateSavedSearch(updatedSearch)];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, updateSearchPromiseResult];
                    case 4:
                        updateSearchResult = _a.sent();
                        expect(updateSearchResult).toEqual({ success: true, result: updatedSearch });
                        expect(updateSavedSearch).toHaveBeenCalledWith(updatedSearch);
                        expect(result.current.states.updating).toBe(RequestStates.LOADED);
                        expect(result.current.data).toEqual([
                            defaultSavedSearchesResponse.result[0],
                            updatedSearch,
                            defaultSavedSearchesResponse.result[2]
                        ]);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should show error message and should not update search in case of updateSavedSearch rejects error', function () { return __awaiter(void 0, void 0, void 0, function () {
            var updateSearchPromiseResult, result, updateSearchResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        expect(result.current.states.updating).toBe(RequestStates.INIT);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    updateSearchPromiseResult = result.current.updateSearch(updatedSearch);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(result.current.states.updating).toBe(RequestStates.LOADING);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, rejectUpdateSavedSearch({ errorMessage: 'Something went wrong' })];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, updateSearchPromiseResult];
                    case 4:
                        updateSearchResult = _a.sent();
                        expect(updateSearchResult).toEqual({ success: false, error: { errorMessage: 'Something went wrong' } });
                        expect(updateSavedSearch).toHaveBeenCalledWith(updatedSearch);
                        expect(result.current.states.updating).toBe(RequestStates.ERROR);
                        expect(result.current.data).toEqual(defaultSavedSearchesResponse.result);
                        expect(showDefaultErrorMessage).toHaveBeenCalledWith({ errorMessage: 'Something went wrong' });
                        return [2 /*return*/];
                }
            });
        }); });
    });
    describe('deleteSearch tests', function () {
        var resolveDeleteSavedSearch, rejectDeleteSavedSearch;
        beforeEach(function () {
            deleteSavedSearch.mockImplementation(function () {
                return new Promise(function (resolve, reject) {
                    resolveDeleteSavedSearch = resolve;
                    rejectDeleteSavedSearch = reject;
                });
            });
        });
        it('should delete search and reload saved searches correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
            var deleteSearchPromiseResult, result, deletedUri, deleteSearchResult, savedSearchesResponse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        getSavedSearches.mockClear();
                        expect(result.current.states.deleting).toBe(RequestStates.INIT);
                        deletedUri = defaultSavedSearchesResponse.result[1].uri;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    deleteSearchPromiseResult = result.current.deleteSearch(deletedUri);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(deleteSavedSearch).toHaveBeenCalledWith({ uri: deletedUri });
                        expect(result.current.states.deleting).toBe(RequestStates.LOADING);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, resolveDeleteSavedSearch({ status: 'success' })];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, deleteSearchPromiseResult];
                    case 4:
                        deleteSearchResult = _a.sent();
                        expect(deleteSearchResult).toEqual({ success: true, result: { status: 'success' } });
                        expect(result.current.states.deleting).toBe(RequestStates.LOADED);
                        expect(getSavedSearches).toHaveBeenCalledWith({ favoriteOnly: true, max: 25, offset: 0 }, signal);
                        expect(result.current.states.loading).toBe(RequestStates.LOADING);
                        savedSearchesResponse = __assign(__assign({}, defaultSavedSearchesResponse), { result: [defaultSavedSearchesResponse.result[0], defaultSavedSearchesResponse.result[2]] });
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(savedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 5:
                        _a.sent();
                        expect(result.current.states.loading).toBe(RequestStates.LOADED);
                        expect(result.current.data).toEqual(savedSearchesResponse.result);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should show error message and should not reload saved searches in case of deleteSavedSearch rejects error', function () { return __awaiter(void 0, void 0, void 0, function () {
            var deleteSearchPromiseResult, result, deletedUri, deleteSearchResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = setUp().result;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    resolveGetSavedSearches(defaultSavedSearchesResponse);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        getSavedSearches.mockClear();
                        expect(result.current.states.deleting).toBe(RequestStates.INIT);
                        deletedUri = defaultSavedSearchesResponse.result[1].uri;
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    deleteSearchPromiseResult = result.current.deleteSearch(deletedUri);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        expect(result.current.states.deleting).toBe(RequestStates.LOADING);
                        return [4 /*yield*/, act(function () { return __awaiter(void 0, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, rejectDeleteSavedSearch({ errorMessage: 'Something went wrong' })];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, deleteSearchPromiseResult];
                    case 4:
                        deleteSearchResult = _a.sent();
                        expect(deleteSearchResult).toEqual({ success: false, error: { errorMessage: 'Something went wrong' } });
                        expect(deleteSavedSearch).toHaveBeenCalledWith({ uri: deletedUri });
                        expect(result.current.states.deleting).toBe(RequestStates.ERROR);
                        expect(result.current.data).toEqual(defaultSavedSearchesResponse.result);
                        expect(getSavedSearches).not.toHaveBeenCalled();
                        expect(showDefaultErrorMessage).toHaveBeenCalledWith({ errorMessage: 'Something went wrong' });
                        return [2 /*return*/];
                }
            });
        }); });
    });
});
