Unverified Commit 32ab7c8b authored by Tamika Tannis's avatar Tamika Tannis Committed by GitHub

Cleanup api methods and imports (#219)

parent 42a544e1
......@@ -2,9 +2,9 @@ import axios, { AxiosResponse } from 'axios';
import { Tag } from 'interfaces';
import { metadataAllTags, AllTagsAPI } from '../v0';
import * as API from '../v0';
describe('metadataAllTags', () => {
describe('getAllTags', () => {
it('resolves with array of sorted result of response.data.tags on success', async () => {
const rawTags: Tag[] = [
{tag_count: 2, tag_name: 'test'},
......@@ -14,7 +14,7 @@ describe('metadataAllTags', () => {
{tag_count: 1, tag_name: 'atest'},
{tag_count: 2, tag_name: 'test'}
];
const mockResponse: AxiosResponse<AllTagsAPI> = {
const mockResponse: AxiosResponse<API.AllTagsAPI> = {
data: {
tags: rawTags,
msg: 'Success'
......@@ -27,7 +27,7 @@ describe('metadataAllTags', () => {
const axiosMock = jest.spyOn(axios, 'get').mockImplementation(() => Promise.resolve(mockResponse));
expect.assertions(1);
await metadataAllTags().then(sortedTags => {
await API.getAllTags().then(sortedTags => {
expect(sortedTags).toEqual(expectedTags);
});
});
......
......@@ -8,7 +8,7 @@ export type AllTagsAPI = {
tags: Tag[];
};
export function metadataAllTags() {
export function getAllTags() {
return axios.get('/api/metadata/v0/tags').then((response: AxiosResponse<AllTagsAPI>) => {
return response.data.tags.sort(sortTagsAlphabetical);
})
......
import { SagaIterator } from 'redux-saga';
import { call, put, takeEvery } from 'redux-saga/effects';
import { metadataAllTags } from './api/v0';
import * as API from './api/v0';
import { getAllTagsFailure, getAllTagsSuccess } from './reducer';
import { GetAllTags } from './types';
export function* getAllTagsWorker(): SagaIterator {
try {
const tags = yield call(metadataAllTags);
const tags = yield call(API.getAllTags);
yield put(getAllTagsSuccess(tags));
} catch (e) {
yield put(getAllTagsFailure());
......
......@@ -2,7 +2,7 @@ import { expectSaga, testSaga } from 'redux-saga-test-plan';
import * as matchers from 'redux-saga-test-plan/matchers';
import { throwError } from 'redux-saga-test-plan/providers';
import { metadataAllTags } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
getAllTags, getAllTagsFailure, getAllTagsSuccess,
initialState, AllTagsReducerState
......@@ -69,8 +69,8 @@ describe('allTags ducks', () => {
describe('getAllTagsWatcher', () => {
it('takes GetAllTags.REQUEST with getAllTagsWorker', () => {
testSaga(getAllTagsWatcher)
.next()
.takeEvery(GetAllTags.REQUEST, getAllTagsWorker);
.next().takeEvery(GetAllTags.REQUEST, getAllTagsWorker)
.next().isDone();
});
});
......@@ -79,7 +79,7 @@ describe('allTags ducks', () => {
const mockTags = [{tag_count: 2, tag_name: 'test'}, {tag_count: 1, tag_name: 'test2'}];
return expectSaga(getAllTagsWorker)
.provide([
[matchers.call.fn(metadataAllTags), mockTags],
[matchers.call.fn(API.getAllTags), mockTags],
])
.put(getAllTagsSuccess(mockTags))
.run();
......@@ -88,7 +88,7 @@ describe('allTags ducks', () => {
it('handles request error', () => {
return expectSaga(getAllTagsWorker)
.provide([
[matchers.call.fn(metadataAllTags), throwError(new Error())],
[matchers.call.fn(API.getAllTags), throwError(new Error())],
])
.put(getAllTagsFailure())
.run();
......
......@@ -2,13 +2,13 @@ import axios, { AxiosResponse } from 'axios';
import { AnnouncementPost } from 'interfaces';
import { announcementsGet, AnnouncementsAPI } from '../v0';
import * as API from '../v0';
jest.mock('axios');
describe('announcementsGet', () => {
describe('getAnnouncements', () => {
let expectedPosts: AnnouncementPost[];
let mockResponse: AxiosResponse<AnnouncementsAPI>;
let mockResponse: AxiosResponse<API.AnnouncementsAPI>;
beforeAll(() => {
expectedPosts = [{ date: '12/31/1999', title: 'Test', html_content: '<div>Test content</div>' }];
mockResponse = {
......@@ -27,13 +27,13 @@ describe('announcementsGet', () => {
it('resolves with array of posts from response.data on success', async () => {
expect.assertions(1);
await announcementsGet().then(posts => {
await API.getAnnouncements().then(posts => {
expect(posts).toEqual(expectedPosts);
});
});
afterAll(() => {
// @ts-ignore: TypeScript errors on Jest mock methods unless we extend AxiosStatic for tests
// @ts-ignore: TypeScript errors on Jest mock methods unless we extend AxiosStatic for tests
axios.mockClear();
})
});
......@@ -7,7 +7,7 @@ export type AnnouncementsAPI = {
posts: AnnouncementPost[];
};
export function announcementsGet() {
export function getAnnouncements() {
return axios({
method: 'get',
url: '/api/announcements/v0/',
......
import { SagaIterator } from 'redux-saga';
import { call, put, takeEvery } from 'redux-saga/effects';
import { announcementsGet } from './api/v0';
import * as API from './api/v0';
import { getAnnouncementsFailure, getAnnouncementsSuccess } from './reducer';
import { GetAnnouncements } from './types';
export function* getAnnouncementsWorker(): SagaIterator {
try {
const posts = yield call(announcementsGet);
const posts = yield call(API.getAnnouncements);
yield put(getAnnouncementsSuccess(posts));
} catch (e) {
yield put(getAnnouncementsFailure());
......
......@@ -2,7 +2,7 @@ import { expectSaga, testSaga } from 'redux-saga-test-plan';
import * as matchers from 'redux-saga-test-plan/matchers';
import { throwError } from 'redux-saga-test-plan/providers';
import { announcementsGet } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
getAnnouncements, getAnnouncementsFailure, getAnnouncementsSuccess,
initialState, AnnouncementsReducerState
......@@ -60,8 +60,8 @@ describe('announcements ducks', () => {
describe('getAnnouncementsWatcher', () => {
it('takes GetAnnouncements.REQUEST with getAnnouncementsWorker', () => {
testSaga(getAnnouncementsWatcher)
.next()
.takeEvery(GetAnnouncements.REQUEST, getAnnouncementsWorker);
.next().takeEvery(GetAnnouncements.REQUEST, getAnnouncementsWorker)
.next().isDone();
});
});
......@@ -70,7 +70,7 @@ describe('announcements ducks', () => {
const mockPosts = [{ date: '12/31/1999', title: 'Test', html_content: '<div>Test content</div>' }];
return expectSaga(getAnnouncementsWorker)
.provide([
[matchers.call.fn(announcementsGet), mockPosts],
[matchers.call.fn(API.getAnnouncements), mockPosts],
])
.put(getAnnouncementsSuccess(mockPosts))
.run();
......@@ -79,7 +79,7 @@ describe('announcements ducks', () => {
it('handles request error', () => {
return expectSaga(getAnnouncementsWorker)
.provide([
[matchers.call.fn(announcementsGet), throwError(new Error())],
[matchers.call.fn(API.getAnnouncements), throwError(new Error())],
])
.put(getAnnouncementsFailure())
.run();
......
......@@ -2,7 +2,7 @@ import axios, { AxiosResponse } from 'axios';
import { Bookmark } from 'interfaces';
import { addBookmark, getBookmarks, removeBookmark, API_PATH } from '../v0';
import * as API from '../v0';
jest.mock('axios');
......@@ -25,14 +25,14 @@ describe('addBookmark', () => {
it('calls axios with correct parameters', async () => {
expect.assertions(1);
await addBookmark('test', 'table').then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API_PATH}/user/bookmark`, { type: 'table', key: 'test' });
await API.addBookmark('test', 'table').then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API.API_PATH}/user/bookmark`, { type: 'table', key: 'test' });
});
});
it('returns response data', async () => {
expect.assertions(1);
await addBookmark('test', 'table').then(data => {
await API.addBookmark('test', 'table').then(data => {
expect(data).toEqual(mockPutResponse.data);
});
});
......@@ -61,21 +61,21 @@ describe('getBookmarks', () => {
it('calls axios with correct parameters if userId provided', async () => {
expect.assertions(1);
await getBookmarks('testUserId').then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API_PATH}/user/bookmark?user_id=testUserId`);
await API.getBookmarks('testUserId').then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API.API_PATH}/user/bookmark?user_id=testUserId`);
});
});
it('calls axios with correct parameters if userId not provided', async () => {
expect.assertions(1);
await getBookmarks().then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API_PATH}/user/bookmark`);
await API.getBookmarks().then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API.API_PATH}/user/bookmark`);
});
});
it('returns response data', async () => {
expect.assertions(1);
await getBookmarks('testUserId').then(data => {
await API.getBookmarks('testUserId').then(data => {
expect(data).toEqual(mockGetResponse.data);
});
});
......@@ -105,14 +105,14 @@ describe('removeBookmark', () => {
it('calls axios with correct parameters', async () => {
expect.assertions(1);
await removeBookmark('testKey', 'table').then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API_PATH}/user/bookmark`, { data: { type: 'table', key: 'testKey' }});
await API.removeBookmark('testKey', 'table').then(data => {
expect(axiosMock).toHaveBeenCalledWith(`${API.API_PATH}/user/bookmark`, { data: { type: 'table', key: 'testKey' }});
});
});
it('returns response data', async () => {
expect.assertions(1);
await removeBookmark('test', 'table').then(data => {
await API.removeBookmark('test', 'table').then(data => {
expect(data).toEqual(mockDeleteResponse.data);
});
});
......
import { SagaIterator } from 'redux-saga';
import { call, put, takeEvery } from 'redux-saga/effects';
import {
addBookmark,
removeBookmark,
getBookmarks,
} from './api/v0';
import * as API from './api/v0';
import {
addBookmarkFailure,
......@@ -34,10 +30,10 @@ export function* addBookmarkWorker(action: AddBookmarkRequest): SagaIterator {
const { resourceKey, resourceType } = action.payload;
try {
yield call(addBookmark, resourceKey, resourceType);
yield call(API.addBookmark, resourceKey, resourceType);
// TODO - Consider adding the newly bookmarked resource directly to local store. This would save a round trip.
response = yield call(getBookmarks);
response = yield call(API.getBookmarks);
yield put(addBookmarkSuccess(response.bookmarks));
} catch(e) {
yield put(addBookmarkFailure());
......@@ -52,7 +48,7 @@ export function* removeBookmarkWorker(action: RemoveBookmarkRequest): SagaIterat
let response;
const { resourceKey, resourceType } = action.payload;
try {
response = yield call(removeBookmark, resourceKey, resourceType);
response = yield call(API.removeBookmark, resourceKey, resourceType);
yield put(removeBookmarkSuccess(resourceKey, resourceType));
} catch(e) {
yield put(removeBookmarkFailure());
......@@ -66,7 +62,7 @@ export function* removeBookmarkWatcher(): SagaIterator {
export function* getBookmarksWorker(action: GetBookmarksRequest): SagaIterator {
let response;
try {
response = yield call(getBookmarks);
response = yield call(API.getBookmarks);
yield put(getBookmarksSuccess(response.bookmarks));
} catch(e) {
yield put(getBookmarksFailure());
......@@ -81,7 +77,7 @@ export function* getBookmarkForUserWorker(action: GetBookmarksForUserRequest): S
let response;
const { userId } = action.payload;
try {
response = yield call(getBookmarks, userId);
response = yield call(API.getBookmarks, userId);
yield put(getBookmarksForUserSuccess(response.bookmarks));
} catch(e) {
yield put(getBookmarksForUserFailure());
......
......@@ -4,7 +4,7 @@ import { throwError } from 'redux-saga-test-plan/providers';
import { Bookmark, ResourceType } from 'interfaces';
import { addBookmark as addBkmrk, getBookmarks as getBkmrks, removeBookmark as removeBkmrk } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
addBookmark, addBookmarkFailure, addBookmarkSuccess,
getBookmarks, getBookmarksFailure, getBookmarksSuccess,
......@@ -222,8 +222,8 @@ describe('bookmark ducks', () => {
describe('addBookmarkWatcher', () => {
it('takes AddBookmark.REQUEST with addBookmarkWorker', () => {
testSaga(addBookmarkWatcher)
.next()
.takeEvery(AddBookmark.REQUEST, addBookmarkWorker);
.next().takeEvery(AddBookmark.REQUEST, addBookmarkWorker)
.next().isDone();
});
});
......@@ -236,8 +236,8 @@ describe('bookmark ducks', () => {
it('adds a bookmark', () => {
return expectSaga(addBookmarkWorker, action)
.provide([
[matchers.call.fn(addBkmrk), {}],
[matchers.call.fn(getBkmrks), { bookmarks }],
[matchers.call.fn(API.addBookmark), {}],
[matchers.call.fn(API.getBookmarks), { bookmarks }],
])
.put(addBookmarkSuccess(bookmarks))
.run();
......@@ -246,8 +246,8 @@ describe('bookmark ducks', () => {
it('handles request error', () => {
return expectSaga(addBookmarkWorker, action)
.provide([
[matchers.call.fn(addBkmrk), throwError(new Error())],
[matchers.call.fn(getBkmrks), throwError(new Error())],
[matchers.call.fn(API.addBookmark), throwError(new Error())],
[matchers.call.fn(API.getBookmarks), throwError(new Error())],
])
.put(addBookmarkFailure())
.run();
......@@ -257,8 +257,8 @@ describe('bookmark ducks', () => {
describe('getBookmarksWatcher', () => {
it('takes GetBookmark.REQUEST with getBookmarksWorker', () => {
testSaga(getBookmarksWatcher)
.next()
.takeEvery(GetBookmarks.REQUEST, getBookmarksWorker);
.next().takeEvery(GetBookmarks.REQUEST, getBookmarksWorker)
.next().isDone();
});
});
......@@ -266,7 +266,7 @@ describe('bookmark ducks', () => {
it('gets bookmarks', () => {
return expectSaga(getBookmarksWorker)
.provide([
[matchers.call.fn(getBkmrks), { bookmarks }],
[matchers.call.fn(API.getBookmarks), { bookmarks }],
])
.put(getBookmarksSuccess(bookmarks))
.run();
......@@ -275,7 +275,7 @@ describe('bookmark ducks', () => {
it('handles request error', () => {
return expectSaga(getBookmarksWorker)
.provide([
[matchers.call.fn(getBkmrks), throwError(new Error())],
[matchers.call.fn(API.getBookmarks), throwError(new Error())],
])
.put(getBookmarksFailure())
.run();
......@@ -285,8 +285,8 @@ describe('bookmark ducks', () => {
describe('getBookmarksForUserWatcher', () => {
it('takes GetBookmarksForUser.REQUEST with getBookmarkForUserWorker', () => {
testSaga(getBookmarksForUserWatcher)
.next()
.takeEvery(GetBookmarksForUser.REQUEST, getBookmarkForUserWorker);
.next().takeEvery(GetBookmarksForUser.REQUEST, getBookmarkForUserWorker)
.next().isDone();
});
});
......@@ -296,10 +296,10 @@ describe('bookmark ducks', () => {
action = getBookmarksForUser(testUserId);
});
it('adds a bookmark', () => {
it('gets bookmarks', () => {
return expectSaga(getBookmarkForUserWorker, action)
.provide([
[matchers.call.fn(getBkmrks), { bookmarks }],
[matchers.call.fn(API.getBookmarks), { bookmarks }],
])
.put(getBookmarksForUserSuccess(bookmarks))
.run();
......@@ -308,7 +308,7 @@ describe('bookmark ducks', () => {
it('handles request error', () => {
return expectSaga(getBookmarkForUserWorker, action)
.provide([
[matchers.call.fn(getBkmrks), throwError(new Error())],
[matchers.call.fn(API.getBookmarks), throwError(new Error())],
])
.put(getBookmarksForUserFailure())
.run();
......@@ -318,8 +318,8 @@ describe('bookmark ducks', () => {
describe('removeBookmarkWatcher', () => {
it('takes RemoveBookmark.REQUEST with removeBookmarkWorker', () => {
testSaga(removeBookmarkWatcher)
.next()
.takeEvery(RemoveBookmark.REQUEST, removeBookmarkWorker);
.next().takeEvery(RemoveBookmark.REQUEST, removeBookmarkWorker)
.next().isDone();
});
});
......@@ -332,7 +332,7 @@ describe('bookmark ducks', () => {
it('removes a bookmark', () => {
return expectSaga(removeBookmarkWorker, action)
.provide([
[matchers.call.fn(removeBkmrk), {}],
[matchers.call.fn(API.removeBookmark), {}],
])
.put(removeBookmarkSuccess(testResourceKey, testResourceType))
.run();
......@@ -341,7 +341,7 @@ describe('bookmark ducks', () => {
it('handles request error', () => {
return expectSaga(removeBookmarkWorker, action)
.provide([
[matchers.call.fn(removeBkmrk), throwError(new Error())],
[matchers.call.fn(API.removeBookmark), throwError(new Error())],
])
.put(removeBookmarkFailure())
.run();
......
import axios from 'axios';
import { feedbackSubmit } from '../v0';
import * as API from '../v0';
jest.mock('axios');
describe('feedbackSubmit', () => {
describe('submitFeedback', () => {
let formData: FormData;
beforeAll(() => {
formData = new FormData();
feedbackSubmit(formData);
API.submitFeedback(formData);
});
it('calls axios with expected payload', () => {
......
import axios from 'axios';
export function feedbackSubmit(data: FormData) {
export function submitFeedback(data: FormData) {
return axios({
data,
method: 'post',
......
import { SagaIterator } from 'redux-saga';
import { call, delay, put, takeEvery } from 'redux-saga/effects';
import { feedbackSubmit } from './api/v0';
import * as API from './api/v0';
import { submitFeedbackFailure, submitFeedbackSuccess, resetFeedback } from './reducer';
import { SubmitFeedback, SubmitFeedbackRequest } from './types';
export function* submitFeedbackWorker(action: SubmitFeedbackRequest): SagaIterator {
try {
yield call(feedbackSubmit, action.payload.data);
yield call(API.submitFeedback, action.payload.data);
yield put(submitFeedbackSuccess());
yield delay(2000);
......
......@@ -2,7 +2,7 @@ import { testSaga } from 'redux-saga-test-plan';
import { SendingState } from 'interfaces';
import { feedbackSubmit } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
submitFeedback,
submitFeedbackFailure,
......@@ -87,37 +87,27 @@ describe('feedback ducks', () => {
describe('submitFeedbackWatcher', () => {
it('takes every SubmitFeedback.REQUEST with submitFeedbackWorker', () => {
testSaga(submitFeedbackWatcher)
.next()
.takeEvery(SubmitFeedback.REQUEST, submitFeedbackWorker);
.next().takeEvery(SubmitFeedback.REQUEST, submitFeedbackWorker)
.next().isDone();
});
});
describe('submitFeedbackWorker', () => {
it('executes submit feedback flow', () => {
testSaga(submitFeedbackWorker, action)
.next()
.call(feedbackSubmit, formData)
.next()
.put(submitFeedbackSuccess())
.next()
.delay(2000)
.next()
.put(resetFeedback())
.next()
.isDone();
.next().call(API.submitFeedback, formData)
.next().put(submitFeedbackSuccess())
.next().delay(2000)
.next().put(resetFeedback())
.next().isDone();
});
it('handles request error', () => {
testSaga(submitFeedbackWorker, action)
.next()
.throw(new Error())
.put(submitFeedbackFailure())
.next()
.delay(2000)
.next()
.put(resetFeedback())
.next()
.isDone();
.next().throw(new Error()).put(submitFeedbackFailure())
.next().delay(2000)
.next().put(resetFeedback())
.next().isDone();
});
});
});
......
import axios from 'axios';
import { postActionLog, BASE_URL, ActionLogParams } from '../v0';
import * as API from '../v0';
jest.mock('axios');
describe('postActionLog', () => {
let axiosMock;
let params: ActionLogParams;
let params: API.ActionLogParams;
beforeAll(() => {
axiosMock = jest.spyOn(axios, 'post').mockImplementation(() => Promise.resolve());
params = {};
postActionLog(params);
API.postActionLog(params);
});
it('calls axios with expected parameters',() => {
expect(axiosMock).toHaveBeenCalledWith(BASE_URL, params);
expect(axiosMock).toHaveBeenCalledWith(API.BASE_URL, params);
});
afterAll(() => {
......
......@@ -4,14 +4,14 @@ import globalState from 'fixtures/globalState';
import { TableResource } from 'interfaces';
import { metadataPopularTables, PopularTablesAPI } from '../v0';
import * as API from '../v0';
jest.mock('axios');
describe('metadataPopularTables', () => {
describe('getPopularTables', () => {
let axiosMock;
let expectedTables: TableResource[];
let mockGetResponse: AxiosResponse<PopularTablesAPI>;
let mockGetResponse: AxiosResponse<API.PopularTablesAPI>;
beforeAll(() => {
expectedTables = globalState.popularTables;
mockGetResponse = {
......@@ -29,7 +29,7 @@ describe('metadataPopularTables', () => {
it('resolves with array of table resources from response.data on success', async () => {
expect.assertions(1);
await metadataPopularTables().then(results => {
await API.getPopularTables().then(results => {
expect(results).toEqual(expectedTables);
});
});
......
......@@ -7,7 +7,7 @@ export type PopularTablesAPI = {
results: TableResource[];
}
export function metadataPopularTables() {
export function getPopularTables() {
return axios.get('/api/metadata/v0/popular_tables')
.then((response: AxiosResponse<PopularTablesAPI>) => {
return response.data.results;
......
import { SagaIterator } from 'redux-saga';
import { call, put, takeEvery } from 'redux-saga/effects';
import { metadataPopularTables} from './api/v0';
import * as API from './api/v0';
import { getPopularTablesFailure, getPopularTablesSuccess } from './reducer';
import { GetPopularTables } from './types';
export function* getPopularTablesWorker(): SagaIterator {
try {
const popularTables = yield call(metadataPopularTables);
const popularTables = yield call(API.getPopularTables);
yield put(getPopularTablesSuccess(popularTables));
} catch (e) {
yield put(getPopularTablesFailure());
......
......@@ -4,7 +4,7 @@ import { TableResource } from 'interfaces';
import globalState from 'fixtures/globalState';
import { metadataPopularTables } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
getPopularTables,
getPopularTablesFailure,
......@@ -66,29 +66,23 @@ describe('popularTables ducks', () => {
describe('getPopularTablesWatcher', () => {
it('takes every GetPopularTables.REQUEST with getPopularTablesWorker', () => {
testSaga(getPopularTablesWatcher)
.next()
.takeEvery(GetPopularTables.REQUEST, getPopularTablesWorker);
.next().takeEvery(GetPopularTables.REQUEST, getPopularTablesWorker)
.next().isDone();
});
});
describe('getPopularTablesWorker', () => {
it('executes flow for returning tables', () => {
testSaga(getPopularTablesWorker)
.next()
.call(metadataPopularTables)
.next(expectedTables)
.put(getPopularTablesSuccess(expectedTables))
.next()
.isDone();
.next().call(API.getPopularTables)
.next(expectedTables).put(getPopularTablesSuccess(expectedTables))
.next().isDone();
});
it('handles request error', () => {
testSaga(getPopularTablesWorker)
.next()
.throw(new Error())
.put(getPopularTablesFailure())
.next()
.isDone();
.next().throw(new Error()).put(getPopularTablesFailure())
.next().isDone();
});
});
});
......
import axios, { AxiosResponse } from 'axios';
import AppConfig from 'config/config';
import { DashboardSearchResults, TableSearchResults, UserSearchResults } from 'ducks/search/types';
import globalState from 'fixtures/globalState';
import { ResourceType, SearchAllOptions } from 'interfaces';
import { searchResource, searchResourceHelper, SearchAPI, BASE_URL } from '../v0';
import * as API from '../v0';
jest.mock('axios');
describe('searchResource', () => {
let axiosMockGet;
let mockTableResponse: AxiosResponse<SearchAPI>;
let mockTableResponse: AxiosResponse<API.SearchAPI>;
beforeAll(() => {
mockTableResponse = {
data: {
......@@ -30,25 +34,51 @@ describe('searchResource', () => {
axiosMockGet = jest.spyOn(axios, 'get').mockImplementation(() => Promise.resolve(mockTableResponse));
});
it('calls axios get with request for a resource', async () => {
const pageIndex = 0;
const resourceType = ResourceType.table;
const term = 'test';
await searchResource(pageIndex, resourceType, term);
expect(axiosMockGet).toHaveBeenCalledWith(`${BASE_URL}/${resourceType}?query=${term}&page_index=${pageIndex}`);
});
describe('searchResource', () => {
it('calls axios get with request for a resource', async () => {
axiosMockGet.mockClear();
const pageIndex = 0;
const resourceType = ResourceType.table;
const term = 'test';
await API.searchResource(pageIndex, resourceType, term);
expect(axiosMockGet).toHaveBeenCalledWith(`${API.BASE_URL}/${resourceType}?query=${term}&page_index=${pageIndex}`);
});
it('calls searchResourceHelper with api call response', async () => {
const searchResourceHelperSpy = jest.spyOn(API, 'searchResourceHelper');
await API.searchResource(0, ResourceType.table, 'test');
expect(searchResourceHelperSpy).toHaveBeenCalledWith(mockTableResponse);
});
it('resolves with empty object if dashboard resource search not supported', async () => {
axiosMockGet.mockClear();
const pageIndex = 0;
const resourceType = ResourceType.dashboard;
const term = 'test';
expect.assertions(2);
await API.searchResource(pageIndex, resourceType, term).then(results => {
expect(results).toEqual({});
});
expect(axiosMockGet).not.toHaveBeenCalled();
});
/*
TODO: Not set up to test this.
it('calls searchResourceHelper with resolved results', async () => {
await searchResource(0, ResourceType.table, 'test');
expect(searchResourceHelper).toHaveBeenCalledWith(mockTableResponse);
it('resolves with empty object if user resource search not supported', async () => {
axiosMockGet.mockClear();
AppConfig.indexUsers.enabled = false;
const pageIndex = 0;
const resourceType = ResourceType.user;
const term = 'test';
expect.assertions(2);
await API.searchResource(pageIndex, resourceType, term).then(results => {
expect(results).toEqual({});
});
expect(axiosMockGet).not.toHaveBeenCalled();
});
});
*/
describe('searchResourceHelper', () => {
it('returns expected object', () => {
expect(searchResourceHelper(mockTableResponse)).toEqual({
expect(API.searchResourceHelper(mockTableResponse)).toEqual({
searchTerm: mockTableResponse.data.search_term,
tables: mockTableResponse.data.tables,
users: mockTableResponse.data.users,
......
......@@ -3,6 +3,8 @@ import { all, call, put, takeEvery } from 'redux-saga/effects';
import { ResourceType } from 'interfaces/Resources';
import * as API from './api/v0';
import {
SearchAll,
SearchAllRequest,
......@@ -10,10 +12,6 @@ import {
SearchResourceRequest,
} from './types';
import {
searchResource,
} from './api/v0';
import {
searchAllSuccess, searchAllFailure,
searchResourceSuccess, searchResourceFailure,
......@@ -23,9 +21,9 @@ export function* searchAllWorker(action: SearchAllRequest): SagaIterator {
const { options, term } = action.payload;
try {
const [tableResponse, userResponse, dashboardResponse] = yield all([
call(searchResource, options.tableIndex, ResourceType.table, term),
call(searchResource, options.userIndex, ResourceType.user, term),
call(searchResource, options.dashboardIndex, ResourceType.dashboard, term),
call(API.searchResource, options.tableIndex, ResourceType.table, term),
call(API.searchResource, options.userIndex, ResourceType.user, term),
call(API.searchResource, options.dashboardIndex, ResourceType.dashboard, term),
]);
const searchAllResponse = {
search_term: term,
......@@ -45,7 +43,7 @@ export function* searchAllWatcher(): SagaIterator {
export function* searchResourceWorker(action: SearchResourceRequest): SagaIterator {
const { pageIndex, resource, term } = action.payload;
try {
const searchResults = yield call(searchResource, pageIndex, resource, term);
const searchResults = yield call(API.searchResource, pageIndex, resource, term);
yield put(searchResourceSuccess(searchResults));
} catch (e) {
yield put(searchResourceFailure());
......
......@@ -4,7 +4,7 @@ import { ResourceType } from 'interfaces';
import globalState from 'fixtures/globalState';
import { searchResource as srchResource } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
searchAll, searchAllSuccess, searchAllFailure,
......@@ -146,8 +146,8 @@ describe('search ducks', () => {
describe('searchAllWatcher', () => {
it('takes every SearchAll.REQUEST with searchAllWorker', () => {
testSaga(searchAllWatcher)
.next()
.takeEvery(SearchAll.REQUEST, searchAllWorker);
.next().takeEvery(SearchAll.REQUEST, searchAllWorker)
.next().isDone();
});
});
......@@ -167,19 +167,16 @@ describe('search ducks', () => {
it('handles request error', () => {
testSaga(searchAllWorker, searchAll('test', {}))
.next()
.throw(new Error())
.put(searchAllFailure())
.next()
.isDone();
.next().throw(new Error()).put(searchAllFailure())
.next().isDone();
});
});
describe('searchResourceWatcher', () => {
it('takes every SearchResource.REQUEST with searchResourceWorker', () => {
testSaga(searchResourceWatcher)
.next()
.takeEvery(SearchResource.REQUEST, searchResourceWorker);
.next().takeEvery(SearchResource.REQUEST, searchResourceWorker)
.next().isDone();
});
});
......@@ -189,21 +186,15 @@ describe('search ducks', () => {
const resource = ResourceType.table;
const term = 'test';
testSaga(searchResourceWorker, searchResource(resource, term, pageIndex))
.next()
.call(srchResource, pageIndex, resource, term)
.next(expectedSearchResults)
.put(searchResourceSuccess(expectedSearchResults))
.next()
.isDone();
.next().call(API.searchResource, pageIndex, resource, term)
.next(expectedSearchResults).put(searchResourceSuccess(expectedSearchResults))
.next().isDone();
});
it('handles request error', () => {
testSaga(searchResourceWorker, searchResource(ResourceType.table, 'test', 0))
.next()
.throw(new Error())
.put(searchResourceFailure())
.next()
.isDone();
.next().throw(new Error()).put(searchResourceFailure())
.next().isDone();
});
});
});
......
import { filterFromObj, sortTagsAlphabetical } from 'ducks/utilMethods';
import { OwnerDict, TableMetadata, Tag, User } from 'interfaces';
import { TableDataAPI } from './v0';
import * as API from './v0';
/**
* Generates the query string parameters needed for requests that act on a particular table resource.
......@@ -13,14 +13,14 @@ export function getTableQueryParams(tableKey: string): string {
/**
* Parses the response for table metadata to create a TableMetadata object
*/
export function getTableDataFromResponseData(responseData: TableDataAPI): TableMetadata {
export function getTableDataFromResponseData(responseData: API.TableDataAPI): TableMetadata {
return filterFromObj(responseData.tableData, ['owners', 'tags']) as TableMetadata;
}
/**
* Parses the response for table metadata to return the array of table owners
*/
export function getTableOwnersFromResponseData(responseData: TableDataAPI): OwnerDict {
export function getTableOwnersFromResponseData(responseData: API.TableDataAPI): OwnerDict {
// TODO: owner needs proper id, until then we have to remember that we are using display_name
const ownerObj = responseData.tableData.owners.reduce((resultObj, currentOwner) => {
resultObj[currentOwner.display_name] = currentOwner as User;
......@@ -32,6 +32,6 @@ export function getTableOwnersFromResponseData(responseData: TableDataAPI): Owne
/**
* Parses the response for table metadata to return an array of sorted table tags
*/
export function getTableTagsFromResponseData(responseData: TableDataAPI): Tag[] {
export function getTableTagsFromResponseData(responseData: API.TableDataAPI): Tag[] {
return responseData.tableData.tags.sort(sortTagsAlphabetical);
}
......@@ -6,15 +6,15 @@ import * as Utils from 'ducks/utilMethods';
import globalState from 'fixtures/globalState';
import { TableData, TableDataAPI } from '../v0';
import * as API from '../v0';
const filterFromObjSpy = jest.spyOn(Utils, 'filterFromObj').mockImplementation(() => {});
jest.mock('axios');
describe('helpers', () => {
let mockResponseData: TableDataAPI;
let tableResponseData: TableData;
let mockResponseData: API.TableDataAPI;
let tableResponseData: API.TableData;
beforeAll(() => {
tableResponseData = {
...globalState.tableMetadata.tableData,
......
......@@ -25,7 +25,7 @@ import {
getTableQueryParams, getTableDataFromResponseData, getTableOwnersFromResponseData, getTableTagsFromResponseData,
} from './helpers';
export function metadataTableTags(tableKey: string) {
export function getTableTags(tableKey: string) {
const tableParams = getTableQueryParams(tableKey);
return axios.get(`${API_PATH}/table?${tableParams}&index=&source=`)
.then((response: AxiosResponse<TableDataAPI>) => {
......@@ -34,7 +34,7 @@ export function metadataTableTags(tableKey: string) {
}
/* TODO: Typing this method generates redux-saga related type errors that needs more dedicated debugging */
export function metadataUpdateTableTags(tagArray, tableKey: string) {
export function updateTableTags(tagArray, tableKey: string) {
const updatePayloads = tagArray.map((tagObject) => {
return {
method: tagObject.methodName,
......@@ -48,7 +48,7 @@ export function metadataUpdateTableTags(tagArray, tableKey: string) {
return updatePayloads.map(payload => { axios(payload) });
}
export function metadataGetTableData(tableKey: string, searchIndex: string, source: string ) {
export function getTableData(tableKey: string, searchIndex: string, source: string ) {
const tableParams = getTableQueryParams(tableKey);
return axios.get(`${API_PATH}/table?${tableParams}&index=${searchIndex}&source=${source}`)
.then((response: AxiosResponse<TableDataAPI>) => {
......@@ -61,7 +61,7 @@ export function metadataGetTableData(tableKey: string, searchIndex: string, sour
});
}
export function metadataGetTableDescription(tableData: TableMetadata) {
export function getTableDescription(tableData: TableMetadata) {
const tableParams = getTableQueryParams(tableData.key);
return axios.get(`${API_PATH}/v0/get_table_description?${tableParams}`)
.then((response: AxiosResponse<DescriptionAPI>) => {
......@@ -70,7 +70,7 @@ export function metadataGetTableDescription(tableData: TableMetadata) {
});
}
export function metadataUpdateTableDescription(description: string, tableData: TableMetadata) {
export function updateTableDescription(description: string, tableData: TableMetadata) {
if (description.length === 0) {
throw new Error();
}
......@@ -83,7 +83,7 @@ export function metadataUpdateTableDescription(description: string, tableData: T
}
}
export function metadataTableOwners(tableKey: string) {
export function getTableOwners(tableKey: string) {
const tableParams = getTableQueryParams(tableKey);
return axios.get(`${API_PATH}/table?${tableParams}&index=&source=`)
.then((response: AxiosResponse<TableDataAPI>) => {
......@@ -92,7 +92,7 @@ export function metadataTableOwners(tableKey: string) {
}
/* TODO: Typing this method generates redux-saga related type errors that need more dedicated debugging */
export function metadataUpdateTableOwner(updateArray, tableKey: string) {
export function updateTableOwner(updateArray, tableKey: string) {
const updatePayloads = updateArray.map((item) => {
return {
method: item.method,
......@@ -106,7 +106,7 @@ export function metadataUpdateTableOwner(updateArray, tableKey: string) {
return updatePayloads.map(payload => { axios(payload) });
}
export function metadataGetColumnDescription(columnIndex: number, tableData: TableMetadata) {
export function getColumnDescription(columnIndex: number, tableData: TableMetadata) {
const tableParams = getTableQueryParams(tableData.key);
const columnName = tableData.columns[columnIndex].name;
return axios.get(`${API_PATH}/get_column_description?${tableParams}&column_name=${columnName}`)
......@@ -116,7 +116,7 @@ export function metadataGetColumnDescription(columnIndex: number, tableData: Tab
});
}
export function metadataUpdateColumnDescription(description: string, columnIndex: number, tableData: TableMetadata) {
export function updateColumnDescription(description: string, columnIndex: number, tableData: TableMetadata) {
if (description.length === 0) {
throw new Error();
}
......@@ -131,14 +131,14 @@ export function metadataUpdateColumnDescription(description: string, columnIndex
}
}
export function metadataGetLastIndexed() {
export function getLastIndexed() {
return axios.get(`${API_PATH}/get_last_indexed`)
.then((response: AxiosResponse<LastIndexedAPI>) => {
return response.data.timestamp;
});
}
export function metadataGetPreviewData(queryParams: PreviewQueryParams) {
export function getPreviewData(queryParams: PreviewQueryParams) {
return axios({
url: '/api/preview/v0/',
method: 'POST',
......
import { SagaIterator } from 'redux-saga';
import { all, call, put, select, takeEvery } from 'redux-saga/effects';
import { metadataUpdateTableOwner, metadataTableOwners } from '../api/v0';
import * as API from '../api/v0';
import { updateTableOwnerFailure, updateTableOwnerSuccess } from './reducer';
......@@ -12,8 +12,8 @@ export function* updateTableOwnerWorker(action: UpdateTableOwnerRequest): SagaIt
const state = yield select();
const tableData = state.tableMetadata.tableData;
try {
yield all(metadataUpdateTableOwner(payload.updateArray, tableData.key));
const newOwners = yield call(metadataTableOwners, tableData.key);
yield all(API.updateTableOwner(payload.updateArray, tableData.key));
const newOwners = yield call(API.getTableOwners, tableData.key);
yield put(updateTableOwnerSuccess(newOwners));
if (payload.onSuccess) {
yield call(payload.onSuccess);
......
......@@ -4,7 +4,7 @@ import { OwnerDict, UpdateMethod, UpdateOwnerPayload } from 'interfaces';
import globalState from 'fixtures/globalState';
import * as apis from '../../api/v0';
import * as API from '../../api/v0';
import reducer, {
updateTableOwner, updateTableOwnerFailure, updateTableOwnerSuccess,
......@@ -16,7 +16,7 @@ import { updateTableOwnerWorker, updateTableOwnerWatcher } from '../sagas';
import { GetTableData, UpdateTableOwner } from '../../types';
const metadataUpdateTableOwnerSpy = jest.spyOn(apis, 'metadataUpdateTableOwner').mockImplementation((payload, key) => []);
const updateTableOwnerSpy = jest.spyOn(API, 'updateTableOwner').mockImplementation((payload, key) => []);
describe('tableMetadata:owners ducks', () => {
let expectedOwners: OwnerDict;
......@@ -131,8 +131,8 @@ describe('tableMetadata:owners ducks', () => {
sagaTest = (action) => {
return testSaga(updateTableOwnerWorker, action)
.next().select()
.next(globalState).all(apis.metadataUpdateTableOwner(updatePayload, globalState.tableMetadata.tableData.key))
.next().call(apis.metadataTableOwners, globalState.tableMetadata.tableData.key)
.next(globalState).all(API.updateTableOwner(updatePayload, globalState.tableMetadata.tableData.key))
.next().call(API.getTableOwners, globalState.tableMetadata.tableData.key)
.next(expectedOwners).put(updateTableOwnerSuccess(expectedOwners));
};
});
......
import { SagaIterator } from 'redux-saga';
import { all, call, put, select, takeEvery } from 'redux-saga/effects';
import {
metadataGetLastIndexed,
metadataGetPreviewData,
metadataGetTableData,
metadataGetColumnDescription,
metadataGetTableDescription,
metadataUpdateColumnDescription,
metadataUpdateTableDescription,
} from './api/v0';
import * as API from './api/v0';
import {
getTableDataFailure, getTableDataSuccess,
......@@ -32,7 +24,7 @@ import {
export function* getTableDataWorker(action: GetTableDataRequest): SagaIterator {
try {
const { key, searchIndex, source } = action.payload;
const { data, owners, statusCode, tags } = yield call(metadataGetTableData, key, searchIndex, source);
const { data, owners, statusCode, tags } = yield call(API.getTableData, key, searchIndex, source);
yield put(getTableDataSuccess(data, owners, statusCode, tags));
} catch (e) {
yield put(getTableDataFailure());
......@@ -47,7 +39,7 @@ export function* getTableDescriptionWorker(action: GetTableDescriptionRequest):
const state = yield select();
let tableData = state.tableMetadata.tableData;
try {
tableData = yield call(metadataGetTableDescription, state.tableMetadata.tableData);
tableData = yield call(API.getTableDescription, state.tableMetadata.tableData);
yield put(getTableDescriptionSuccess(tableData));
if (payload.onSuccess) {
yield call(payload.onSuccess);
......@@ -67,7 +59,7 @@ export function* updateTableDescriptionWorker(action: UpdateTableDescriptionRequ
const { payload } = action;
const state = yield select();
try {
yield call(metadataUpdateTableDescription, payload.newValue, state.tableMetadata.tableData);
yield call(API.updateTableDescription, payload.newValue, state.tableMetadata.tableData);
if (payload.onSuccess) {
yield call(payload.onSuccess);
}
......@@ -86,7 +78,7 @@ export function* getColumnDescriptionWorker(action: GetColumnDescriptionRequest)
const state = yield select();
let tableData = state.tableMetadata.tableData;
try {
tableData = yield call(metadataGetColumnDescription, payload.columnIndex, state.tableMetadata.tableData);
tableData = yield call(API.getColumnDescription, payload.columnIndex, state.tableMetadata.tableData);
yield put(getColumnDescriptionSuccess(tableData));
if (payload.onSuccess) {
yield call(payload.onSuccess);
......@@ -106,7 +98,7 @@ export function* updateColumnDescriptionWorker(action: UpdateColumnDescriptionRe
const { payload } = action;
const state = yield select();
try {
yield call(metadataUpdateColumnDescription, payload.newValue, payload.columnIndex, state.tableMetadata.tableData);
yield call(API.updateColumnDescription, payload.newValue, payload.columnIndex, state.tableMetadata.tableData);
if (payload.onSuccess) {
yield call(payload.onSuccess);
}
......@@ -122,7 +114,7 @@ export function* updateColumnDescriptionWatcher(): SagaIterator {
export function* getLastIndexedWorker(action: GetLastIndexedRequest): SagaIterator {
try {
const lastIndexed = yield call(metadataGetLastIndexed);
const lastIndexed = yield call(API.getLastIndexed);
yield put(getLastIndexedSuccess(lastIndexed));
} catch (e) {
yield put(getLastIndexedFailure());
......@@ -134,7 +126,7 @@ export function* getLastIndexedWatcher(): SagaIterator {
export function* getPreviewDataWorker(action: GetPreviewDataRequest): SagaIterator {
try {
const response = yield call(metadataGetPreviewData, action.payload.queryParams);
const response = yield call(API.getPreviewData, action.payload.queryParams);
const { data, status } = response;
yield put(getPreviewDataSuccess(data, status));
} catch (e) {
......
import { SagaIterator } from 'redux-saga';
import { all, call, put, select, takeEvery } from 'redux-saga/effects';
import { metadataUpdateTableTags, metadataTableTags } from '../api/v0';
import * as API from '../api/v0';
import { updateTagsFailure, updateTagsSuccess } from './reducer';
......@@ -11,8 +11,8 @@ export function* updateTableTagsWorker(action: UpdateTagsRequest): SagaIterator
const state = yield select();
const tableData = state.tableMetadata.tableData;
try {
yield all(metadataUpdateTableTags(action.payload.tagArray, tableData.key));
const newTags = yield call(metadataTableTags, tableData.key);
yield all(API.updateTableTags(action.payload.tagArray, tableData.key));
const newTags = yield call(API.getTableTags, tableData.key);
yield put(updateTagsSuccess(newTags));
} catch (e) {
yield put(updateTagsFailure());
......
......@@ -4,7 +4,7 @@ import { UpdateMethod, UpdateTagData, Tag } from 'interfaces';
import globalState from 'fixtures/globalState';
import * as apis from '../../api/v0';
import * as API from '../../api/v0';
import reducer, {
updateTags, updateTagsFailure, updateTagsSuccess,
......@@ -16,7 +16,7 @@ import { updateTableTagsWorker, updateTableTagsWatcher } from '../sagas';
import { GetTableData, UpdateTags } from '../../types';
const metadataUpdateTableTagsSpy = jest.spyOn(apis, 'metadataUpdateTableTags').mockImplementation((payload, key) => []);
const updateTableTagsSpy = jest.spyOn(API, 'updateTableTags').mockImplementation((payload, key) => []);
describe('tableMetadata:tags ducks', () => {
let expectedTags: Tag[];
......@@ -119,8 +119,8 @@ describe('tableMetadata:tags ducks', () => {
it('executes flow for updating tags and returning up to date tag array', () => {
testSaga(updateTableTagsWorker, updateTags(updatePayload))
.next().select()
.next(globalState).all(apis.metadataUpdateTableTags(updatePayload, globalState.tableMetadata.tableData.key))
.next().call(apis.metadataTableTags, globalState.tableMetadata.tableData.key)
.next(globalState).all(API.updateTableTags(updatePayload, globalState.tableMetadata.tableData.key))
.next().call(API.getTableTags, globalState.tableMetadata.tableData.key)
.next(expectedTags).put(updateTagsSuccess(expectedTags))
.next().isDone();
});
......
......@@ -4,15 +4,7 @@ import { PreviewData, PreviewQueryParams, TableMetadata, Tag, UpdateMethod, Upda
import globalState from 'fixtures/globalState';
import {
metadataGetLastIndexed,
metadataGetPreviewData,
metadataGetTableData,
metadataGetColumnDescription,
metadataGetTableDescription,
metadataUpdateColumnDescription,
metadataUpdateTableDescription,
} from '../api/v0';
import * as API from '../api/v0';
import reducer, {
getTableData, getTableDataFailure, getTableDataSuccess,
......@@ -317,7 +309,8 @@ describe('reducer', () => {
describe('getTableDataWatcher', () => {
it('takes every GetTableData.REQUEST with getTableDataWorker', () => {
testSaga(getTableDataWatcher)
.next().takeEvery(GetTableData.REQUEST, getTableDataWorker);
.next().takeEvery(GetTableData.REQUEST, getTableDataWorker)
.next().isDone();
});
});
......@@ -325,7 +318,7 @@ describe('reducer', () => {
it('executes flow for getting table data', () => {
const mockResult = { data: expectedData, owners: expectedOwners, statusCode: expectedStatus, tags: expectedTags };
testSaga(getTableDataWorker, getTableData(testKey, testIndex, testSource))
.next().call(metadataGetTableData, testKey, testIndex, testSource)
.next().call(API.getTableData, testKey, testIndex, testSource)
.next(mockResult).put(getTableDataSuccess(expectedData, expectedOwners, expectedStatus, expectedTags))
.next().isDone();
});
......@@ -340,7 +333,8 @@ describe('reducer', () => {
describe('getTableDescriptionWatcher', () => {
it('takes every GetTableDescription.REQUEST with getTableDescriptionWorker', () => {
testSaga(getTableDescriptionWatcher)
.next().takeEvery(GetTableDescription.REQUEST, getTableDescriptionWorker);
.next().takeEvery(GetTableDescription.REQUEST, getTableDescriptionWorker)
.next().isDone();
});
});
......@@ -352,7 +346,7 @@ describe('reducer', () => {
sagaTest = (action) => {
return testSaga(getTableDescriptionWorker, action)
.next().select()
.next(globalState).call(metadataGetTableDescription, globalState.tableMetadata.tableData)
.next(globalState).call(API.getTableDescription, globalState.tableMetadata.tableData)
.next(mockNewTableData).put(getTableDescriptionSuccess(mockNewTableData))
};
});
......@@ -394,7 +388,8 @@ describe('reducer', () => {
describe('updateTableDescriptionWatcher', () => {
it('takes every UpdateTableDescription.REQUEST with updateTableDescriptionWorker', () => {
testSaga(updateTableDescriptionWatcher)
.next().takeEvery(UpdateTableDescription.REQUEST, updateTableDescriptionWorker);
.next().takeEvery(UpdateTableDescription.REQUEST, updateTableDescriptionWorker)
.next().isDone();
});
});
......@@ -405,7 +400,7 @@ describe('reducer', () => {
sagaTest = (mockSuccess) => {
return testSaga(updateTableDescriptionWorker, updateTableDescription(newDescription, mockSuccess, null))
.next().select()
.next(globalState).call(metadataUpdateTableDescription, newDescription, globalState.tableMetadata.tableData)
.next(globalState).call(API.updateTableDescription, newDescription, globalState.tableMetadata.tableData)
};
});
it('without success callback', () => {
......@@ -445,7 +440,8 @@ describe('reducer', () => {
describe('getColumnDescriptionWatcher', () => {
it('takes every GetColumnDescription.REQUEST with getColumnDescriptionWorker', () => {
testSaga(getColumnDescriptionWatcher)
.next().takeEvery(GetColumnDescription.REQUEST, getColumnDescriptionWorker);
.next().takeEvery(GetColumnDescription.REQUEST, getColumnDescriptionWorker)
.next().isDone();
});
});
......@@ -457,7 +453,7 @@ describe('reducer', () => {
sagaTest = (action) => {
return testSaga(getColumnDescriptionWorker, action)
.next().select()
.next(globalState).call(metadataGetColumnDescription, action.payload.columnIndex, globalState.tableMetadata.tableData)
.next(globalState).call(API.getColumnDescription, action.payload.columnIndex, globalState.tableMetadata.tableData)
.next(mockNewTableData).put(getColumnDescriptionSuccess(mockNewTableData))
};
});
......@@ -499,7 +495,8 @@ describe('reducer', () => {
describe('updateColumnDescriptionWatcher', () => {
it('takes every UpdateColumnDescription.REQUEST with updateColumnDescriptionWorker', () => {
testSaga(updateColumnDescriptionWatcher)
.next().takeEvery(UpdateColumnDescription.REQUEST, updateColumnDescriptionWorker);
.next().takeEvery(UpdateColumnDescription.REQUEST, updateColumnDescriptionWorker)
.next().isDone();
});
});
......@@ -510,7 +507,7 @@ describe('reducer', () => {
sagaTest = (mockSuccess) => {
return testSaga(updateColumnDescriptionWorker, updateColumnDescription(newDescription, columnIndex, mockSuccess, null))
.next().select()
.next(globalState).call(metadataUpdateColumnDescription, newDescription, columnIndex, globalState.tableMetadata.tableData)
.next(globalState).call(API.updateColumnDescription, newDescription, columnIndex, globalState.tableMetadata.tableData)
};
});
it('without success callback', () => {
......@@ -550,14 +547,15 @@ describe('reducer', () => {
describe('getLastIndexedWatcher', () => {
it('takes every GetLastIndexed.REQUEST with getLastIndexedWorker', () => {
testSaga(getLastIndexedWatcher)
.next().takeEvery(GetLastIndexed.REQUEST, getLastIndexedWorker);
.next().takeEvery(GetLastIndexed.REQUEST, getLastIndexedWorker)
.next().isDone();
});
});
describe('getLastIndexedWorker', () => {
it('executes flow for getting last indexed value', () => {
testSaga(getLastIndexedWorker, getLastIndexed())
.next().call(metadataGetLastIndexed)
.next().call(API.getLastIndexed)
.next(testEpoch).put(getLastIndexedSuccess(testEpoch))
.next().isDone();
});
......@@ -572,7 +570,8 @@ describe('reducer', () => {
describe('getPreviewDataWatcher', () => {
it('takes every GetPreviewData.REQUEST with getPreviewDataWorker', () => {
testSaga(getPreviewDataWatcher)
.next().takeEvery(GetPreviewData.REQUEST, getPreviewDataWorker);
.next().takeEvery(GetPreviewData.REQUEST, getPreviewDataWorker)
.next().isDone();
});
});
......@@ -580,7 +579,7 @@ describe('reducer', () => {
it('executes flow for getting preview data', () => {
const mockResponse = { data: previewData, status: 200 };
testSaga(getPreviewDataWorker, getPreviewData(queryParams))
.next().call(metadataGetPreviewData, queryParams)
.next().call(API.getPreviewData, queryParams)
.next(mockResponse).put(getPreviewDataSuccess(previewData, 200))
.next().isDone();
});
......
......@@ -4,16 +4,13 @@ import globalState from 'fixtures/globalState';
import { LoggedInUser, PeopleUser, Resource } from 'interfaces';
import {
loggedInUser, userById, userOwn, userRead,
LoggedInUserAPI, UserAPI, UserOwnAPI, UserReadAPI
} from '../v0';
import * as API from '../v0';
jest.mock('axios');
describe('loggedInUser', () => {
describe('getLoggedInUser', () => {
let axiosMock;
let mockGetResponse: AxiosResponse<LoggedInUserAPI>;
let mockGetResponse: AxiosResponse<API.LoggedInUserAPI>;
let testUser: LoggedInUser;
beforeAll(() => {
testUser = globalState.user.loggedInUser;
......@@ -32,14 +29,14 @@ describe('loggedInUser', () => {
it('calls axios with correct parameters', async () => {
expect.assertions(1);
await loggedInUser().then(user => {
await API.getLoggedInUser().then(user => {
expect(axiosMock).toHaveBeenCalledWith(`/api/auth_user`);
});
});
it('returns user from response data', async () => {
expect.assertions(1);
await loggedInUser().then(user => {
await API.getLoggedInUser().then(user => {
expect(user).toBe(testUser);
});
});
......@@ -49,9 +46,9 @@ describe('loggedInUser', () => {
})
});
describe('userById', () => {
describe('getUser', () => {
let axiosMock;
let mockGetResponse: AxiosResponse<UserAPI>;
let mockGetResponse: AxiosResponse<API.UserAPI>;
let testId: string;
let testUser: PeopleUser;
beforeAll(() => {
......@@ -72,14 +69,14 @@ describe('userById', () => {
it('calls axios with correct parameters', async () => {
expect.assertions(1);
await userById(testId).then(user => {
await API.getUser(testId).then(user => {
expect(axiosMock).toHaveBeenCalledWith(`/api/metadata/v0/user?user_id=${testId}`);
});
});
it('returns user from response data', async () => {
expect.assertions(1);
await userById(testId).then(user => {
await API.getUser(testId).then(user => {
expect(user).toBe(testUser);
});
});
......@@ -89,9 +86,9 @@ describe('userById', () => {
})
});
describe('userOwn', () => {
describe('getUserOwn', () => {
let axiosMock;
let mockGetResponse: AxiosResponse<UserOwnAPI>;
let mockGetResponse: AxiosResponse<API.UserOwnAPI>;
let testId: string;
let testResources: Resource[];
beforeAll(() => {
......@@ -112,14 +109,14 @@ describe('userOwn', () => {
it('calls axios with correct parameters', async () => {
expect.assertions(1);
await userOwn(testId).then(data => {
await API.getUserOwn(testId).then(data => {
expect(axiosMock).toHaveBeenCalledWith(`/api/metadata/v0/user/own?user_id=${testId}`);
});
});
it('returns response data with owned resources', async () => {
expect.assertions(1);
await userOwn(testId).then(data => {
await API.getUserOwn(testId).then(data => {
expect(data.own).toBe(testResources);
});
});
......@@ -129,9 +126,9 @@ describe('userOwn', () => {
})
});
describe('userRead', () => {
describe('getUserRead', () => {
let axiosMock;
let mockGetResponse: AxiosResponse<UserReadAPI>;
let mockGetResponse: AxiosResponse<API.UserReadAPI>;
let testId: string;
let testResources: Resource[];
beforeAll(() => {
......@@ -152,14 +149,14 @@ describe('userRead', () => {
it('calls axios with correct parameters', async () => {
expect.assertions(1);
await userRead(testId).then(data => {
await API.getUserRead(testId).then(data => {
expect(axiosMock).toHaveBeenCalledWith(`/api/metadata/v0/user/read?user_id=${testId}`);
});
});
it('returns response data with frequently read resources', async () => {
expect.assertions(1);
await userRead(testId).then(data => {
await API.getUserRead(testId).then(data => {
expect(data.read).toBe(testResources);
});
});
......
......@@ -7,28 +7,28 @@ export type UserAPI = { user: PeopleUser; msg: string; };
export type UserOwnAPI = { own: Resource[], msg: string; };
export type UserReadAPI = { read: Resource[], msg: string; };
export function loggedInUser() {
export function getLoggedInUser() {
return axios.get(`/api/auth_user`)
.then((response: AxiosResponse<LoggedInUserAPI>) => {
return response.data.user;
});
}
export function userById(userId: string) {
export function getUser(userId: string) {
return axios.get(`/api/metadata/v0/user?user_id=${userId}`)
.then((response: AxiosResponse<UserAPI>) => {
return response.data.user;
});
}
export function userOwn(userId: string) {
export function getUserOwn(userId: string) {
return axios.get(`/api/metadata/v0/user/own?user_id=${userId}`)
.then((response: AxiosResponse<UserOwnAPI>) => {
return response.data
});
}
export function userRead(userId: string) {
export function getUserRead(userId: string) {
return axios.get(`/api/metadata/v0/user/read?user_id=${userId}`)
.then((response: AxiosResponse<UserReadAPI>) => {
return response.data
......
import { SagaIterator } from 'redux-saga';
import { call, put, takeEvery } from 'redux-saga/effects';
import { loggedInUser, userById, userOwn, userRead } from './api/v0';
import * as API from './api/v0';
import {
GetLoggedInUser,
......@@ -22,7 +22,7 @@ import {
export function* getLoggedInUserWorker(): SagaIterator {
try {
const user = yield call(loggedInUser);
const user = yield call(API.getLoggedInUser);
yield put(getLoggedInUserSuccess(user));
} catch (e) {
yield put(getLoggedInUserFailure());
......@@ -34,7 +34,7 @@ export function* getLoggedInUserWatcher(): SagaIterator {
export function* getUserWorker(action: GetUserRequest): SagaIterator {
try {
const user = yield call(userById, action.payload.userId);
const user = yield call(API.getUser, action.payload.userId);
yield put(getUserSuccess(user));
} catch (e) {
yield put(getUserFailure());
......@@ -46,7 +46,7 @@ export function* getUserWatcher(): SagaIterator {
export function* getUserOwnWorker(action: GetUserOwnRequest): SagaIterator {
try {
const responseData = yield call(userOwn, action.payload.userId);
const responseData = yield call(API.getUserOwn, action.payload.userId);
yield put(getUserOwnSuccess(responseData.own));
} catch (e) {
yield put(getUserOwnFailure())
......@@ -59,7 +59,7 @@ export function* getUserOwnWatcher(): SagaIterator {
export function* getUserReadWorker(action: GetUserReadRequest): SagaIterator {
try {
const responseData = yield call(userRead, action.payload.userId);
const responseData = yield call(API.getUserRead, action.payload.userId);
yield put(getUserReadSuccess(responseData.read));
} catch (e) {
yield put(getUserReadFailure())
......
......@@ -4,7 +4,7 @@ import { LoggedInUser, PeopleUser, Resource } from 'interfaces';
import globalState from 'fixtures/globalState';
import { loggedInUser, userById, userOwn, userRead } from '../api/v0';
import * as API from '../api/v0';
import reducer, {
getLoggedInUser, getLoggedInUserFailure, getLoggedInUserSuccess,
getUser, getUserFailure, getUserSuccess,
......@@ -233,7 +233,7 @@ describe('user ducks', () => {
describe('getLoggedInUserWorker', () => {
it('executes flow for returning the currentUser', () => {
testSaga(getLoggedInUserWorker, getLoggedInUser())
.next().call(loggedInUser)
.next().call(API.getLoggedInUser)
.next(currentUser).put(getLoggedInUserSuccess(currentUser))
.next().isDone();
});
......@@ -255,7 +255,7 @@ describe('user ducks', () => {
describe('getUserWorker', () => {
it('executes flow for returning a user given an id', () => {
testSaga(getUserWorker, getUser(userId))
.next().call(userById, userId)
.next().call(API.getUser, userId)
.next(otherUser.user).put(getUserSuccess(otherUser.user))
.next().isDone();
});
......@@ -277,7 +277,7 @@ describe('user ducks', () => {
describe('getUserOwnWorker', () => {
it('executes flow for returning a users owned resources given an id', () => {
testSaga(getUserOwnWorker, getUserOwn(userId))
.next().call(userOwn, userId)
.next().call(API.getUserOwn, userId)
.next(otherUser).put(getUserOwnSuccess(otherUser.own))
.next().isDone();
});
......@@ -299,7 +299,7 @@ describe('user ducks', () => {
describe('getUserReadWorker', () => {
it('executes flow for returning a users frequently used resources given an id', () => {
testSaga(getUserReadWorker, getUserRead(userId))
.next().call(userRead, userId)
.next().call(API.getUserRead, userId)
.next(otherUser).put(getUserReadSuccess(otherUser.read))
.next().isDone();
});
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment