Commit 6b5da5f7 authored by David O'Regan's avatar David O'Regan

Merge branch 'vs/remove-jest-test-callback-part-three' into 'master'

Remove jest test callbacks from specs (2/3)

See merge request gitlab-org/gitlab!84480
parents 59217ae2 5e9fc348
...@@ -42,9 +42,9 @@ describe('AddContextCommitsModalStoreActions', () => { ...@@ -42,9 +42,9 @@ describe('AddContextCommitsModalStoreActions', () => {
}); });
describe('setBaseConfig', () => { describe('setBaseConfig', () => {
it('commits SET_BASE_CONFIG', (done) => { it('commits SET_BASE_CONFIG', () => {
const options = { contextCommitsPath, mergeRequestIid, projectId }; const options = { contextCommitsPath, mergeRequestIid, projectId };
testAction( return testAction(
setBaseConfig, setBaseConfig,
options, options,
{ {
...@@ -59,62 +59,54 @@ describe('AddContextCommitsModalStoreActions', () => { ...@@ -59,62 +59,54 @@ describe('AddContextCommitsModalStoreActions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('setTabIndex', () => { describe('setTabIndex', () => {
it('commits SET_TABINDEX', (done) => { it('commits SET_TABINDEX', () => {
testAction( return testAction(
setTabIndex, setTabIndex,
{ tabIndex: 1 }, { tabIndex: 1 },
{ tabIndex: 0 }, { tabIndex: 0 },
[{ type: types.SET_TABINDEX, payload: { tabIndex: 1 } }], [{ type: types.SET_TABINDEX, payload: { tabIndex: 1 } }],
[], [],
done,
); );
}); });
}); });
describe('setCommits', () => { describe('setCommits', () => {
it('commits SET_COMMITS', (done) => { it('commits SET_COMMITS', () => {
testAction( return testAction(
setCommits, setCommits,
{ commits: [], silentAddition: false }, { commits: [], silentAddition: false },
{ isLoadingCommits: false, commits: [] }, { isLoadingCommits: false, commits: [] },
[{ type: types.SET_COMMITS, payload: [] }], [{ type: types.SET_COMMITS, payload: [] }],
[], [],
done,
); );
}); });
it('commits SET_COMMITS_SILENT', (done) => { it('commits SET_COMMITS_SILENT', () => {
testAction( return testAction(
setCommits, setCommits,
{ commits: [], silentAddition: true }, { commits: [], silentAddition: true },
{ isLoadingCommits: true, commits: [] }, { isLoadingCommits: true, commits: [] },
[{ type: types.SET_COMMITS_SILENT, payload: [] }], [{ type: types.SET_COMMITS_SILENT, payload: [] }],
[], [],
done,
); );
}); });
}); });
describe('createContextCommits', () => { describe('createContextCommits', () => {
it('calls API to create context commits', (done) => { it('calls API to create context commits', async () => {
mock.onPost(contextCommitEndpoint).reply(200, {}); mock.onPost(contextCommitEndpoint).reply(200, {});
testAction(createContextCommits, { commits: [] }, {}, [], [], done); await testAction(createContextCommits, { commits: [] }, {}, [], []);
createContextCommits( await createContextCommits(
{ state: { projectId, mergeRequestIid }, commit: () => null }, { state: { projectId, mergeRequestIid }, commit: () => null },
{ commits: [] }, { commits: [] },
) );
.then(() => {
done();
})
.catch(done.fail);
}); });
}); });
...@@ -126,9 +118,9 @@ describe('AddContextCommitsModalStoreActions', () => { ...@@ -126,9 +118,9 @@ describe('AddContextCommitsModalStoreActions', () => {
) )
.reply(200, [dummyCommit]); .reply(200, [dummyCommit]);
}); });
it('commits FETCH_CONTEXT_COMMITS', (done) => { it('commits FETCH_CONTEXT_COMMITS', () => {
const contextCommit = { ...dummyCommit, isSelected: true }; const contextCommit = { ...dummyCommit, isSelected: true };
testAction( return testAction(
fetchContextCommits, fetchContextCommits,
null, null,
{ {
...@@ -144,20 +136,18 @@ describe('AddContextCommitsModalStoreActions', () => { ...@@ -144,20 +136,18 @@ describe('AddContextCommitsModalStoreActions', () => {
{ type: 'setCommits', payload: { commits: [contextCommit], silentAddition: true } }, { type: 'setCommits', payload: { commits: [contextCommit], silentAddition: true } },
{ type: 'setSelectedCommits', payload: [contextCommit] }, { type: 'setSelectedCommits', payload: [contextCommit] },
], ],
done,
); );
}); });
}); });
describe('setContextCommits', () => { describe('setContextCommits', () => {
it('commits SET_CONTEXT_COMMITS', (done) => { it('commits SET_CONTEXT_COMMITS', () => {
testAction( return testAction(
setContextCommits, setContextCommits,
{ data: [] }, { data: [] },
{ contextCommits: [], isLoadingContextCommits: false }, { contextCommits: [], isLoadingContextCommits: false },
[{ type: types.SET_CONTEXT_COMMITS, payload: { data: [] } }], [{ type: types.SET_CONTEXT_COMMITS, payload: { data: [] } }],
[], [],
done,
); );
}); });
}); });
...@@ -168,71 +158,66 @@ describe('AddContextCommitsModalStoreActions', () => { ...@@ -168,71 +158,66 @@ describe('AddContextCommitsModalStoreActions', () => {
.onDelete('/api/v4/projects/gitlab-org%2Fgitlab/merge_requests/1/context_commits') .onDelete('/api/v4/projects/gitlab-org%2Fgitlab/merge_requests/1/context_commits')
.reply(204); .reply(204);
}); });
it('calls API to remove context commits', (done) => { it('calls API to remove context commits', () => {
testAction( return testAction(
removeContextCommits, removeContextCommits,
{ forceReload: false }, { forceReload: false },
{ mergeRequestIid, projectId, toRemoveCommits: [] }, { mergeRequestIid, projectId, toRemoveCommits: [] },
[], [],
[], [],
done,
); );
}); });
}); });
describe('setSelectedCommits', () => { describe('setSelectedCommits', () => {
it('commits SET_SELECTED_COMMITS', (done) => { it('commits SET_SELECTED_COMMITS', () => {
testAction( return testAction(
setSelectedCommits, setSelectedCommits,
[dummyCommit], [dummyCommit],
{ selectedCommits: [] }, { selectedCommits: [] },
[{ type: types.SET_SELECTED_COMMITS, payload: [dummyCommit] }], [{ type: types.SET_SELECTED_COMMITS, payload: [dummyCommit] }],
[], [],
done,
); );
}); });
}); });
describe('setSearchText', () => { describe('setSearchText', () => {
it('commits SET_SEARCH_TEXT', (done) => { it('commits SET_SEARCH_TEXT', () => {
const searchText = 'Dummy Text'; const searchText = 'Dummy Text';
testAction( return testAction(
setSearchText, setSearchText,
searchText, searchText,
{ searchText: '' }, { searchText: '' },
[{ type: types.SET_SEARCH_TEXT, payload: searchText }], [{ type: types.SET_SEARCH_TEXT, payload: searchText }],
[], [],
done,
); );
}); });
}); });
describe('setToRemoveCommits', () => { describe('setToRemoveCommits', () => {
it('commits SET_TO_REMOVE_COMMITS', (done) => { it('commits SET_TO_REMOVE_COMMITS', () => {
const commitId = 'abcde'; const commitId = 'abcde';
testAction( return testAction(
setToRemoveCommits, setToRemoveCommits,
[commitId], [commitId],
{ toRemoveCommits: [] }, { toRemoveCommits: [] },
[{ type: types.SET_TO_REMOVE_COMMITS, payload: [commitId] }], [{ type: types.SET_TO_REMOVE_COMMITS, payload: [commitId] }],
[], [],
done,
); );
}); });
}); });
describe('resetModalState', () => { describe('resetModalState', () => {
it('commits RESET_MODAL_STATE', (done) => { it('commits RESET_MODAL_STATE', () => {
const commitId = 'abcde'; const commitId = 'abcde';
testAction( return testAction(
resetModalState, resetModalState,
null, null,
{ toRemoveCommits: [commitId] }, { toRemoveCommits: [commitId] },
[{ type: types.RESET_MODAL_STATE }], [{ type: types.RESET_MODAL_STATE }],
[], [],
done,
); );
}); });
}); });
......
...@@ -22,8 +22,8 @@ describe('Admin statistics panel actions', () => { ...@@ -22,8 +22,8 @@ describe('Admin statistics panel actions', () => {
mock.onGet(/api\/(.*)\/application\/statistics/).replyOnce(200, mockStatistics); mock.onGet(/api\/(.*)\/application\/statistics/).replyOnce(200, mockStatistics);
}); });
it('dispatches success with received data', (done) => it('dispatches success with received data', () => {
testAction( return testAction(
actions.fetchStatistics, actions.fetchStatistics,
null, null,
state, state,
...@@ -37,8 +37,8 @@ describe('Admin statistics panel actions', () => { ...@@ -37,8 +37,8 @@ describe('Admin statistics panel actions', () => {
), ),
}, },
], ],
done, );
)); });
}); });
describe('error', () => { describe('error', () => {
...@@ -46,8 +46,8 @@ describe('Admin statistics panel actions', () => { ...@@ -46,8 +46,8 @@ describe('Admin statistics panel actions', () => {
mock.onGet(/api\/(.*)\/application\/statistics/).replyOnce(500); mock.onGet(/api\/(.*)\/application\/statistics/).replyOnce(500);
}); });
it('dispatches error', (done) => it('dispatches error', () => {
testAction( return testAction(
actions.fetchStatistics, actions.fetchStatistics,
null, null,
state, state,
...@@ -61,26 +61,26 @@ describe('Admin statistics panel actions', () => { ...@@ -61,26 +61,26 @@ describe('Admin statistics panel actions', () => {
payload: new Error('Request failed with status code 500'), payload: new Error('Request failed with status code 500'),
}, },
], ],
done, );
)); });
}); });
}); });
describe('requestStatistic', () => { describe('requestStatistic', () => {
it('should commit the request mutation', (done) => it('should commit the request mutation', () => {
testAction( return testAction(
actions.requestStatistics, actions.requestStatistics,
null, null,
state, state,
[{ type: types.REQUEST_STATISTICS }], [{ type: types.REQUEST_STATISTICS }],
[], [],
done, );
)); });
}); });
describe('receiveStatisticsSuccess', () => { describe('receiveStatisticsSuccess', () => {
it('should commit received data', (done) => it('should commit received data', () => {
testAction( return testAction(
actions.receiveStatisticsSuccess, actions.receiveStatisticsSuccess,
mockStatistics, mockStatistics,
state, state,
...@@ -91,13 +91,13 @@ describe('Admin statistics panel actions', () => { ...@@ -91,13 +91,13 @@ describe('Admin statistics panel actions', () => {
}, },
], ],
[], [],
done, );
)); });
}); });
describe('receiveStatisticsError', () => { describe('receiveStatisticsError', () => {
it('should commit error', (done) => { it('should commit error', () => {
testAction( return testAction(
actions.receiveStatisticsError, actions.receiveStatisticsError,
500, 500,
state, state,
...@@ -108,7 +108,6 @@ describe('Admin statistics panel actions', () => { ...@@ -108,7 +108,6 @@ describe('Admin statistics panel actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
......
...@@ -36,24 +36,19 @@ describe('U2FAuthenticate', () => { ...@@ -36,24 +36,19 @@ describe('U2FAuthenticate', () => {
window.u2f = oldu2f; window.u2f = oldu2f;
}); });
it('falls back to normal 2fa', (done) => { it('falls back to normal 2fa', async () => {
component await component.start();
.start() expect(component.switchToFallbackUI).toHaveBeenCalled();
.then(() => {
expect(component.switchToFallbackUI).toHaveBeenCalled();
done();
})
.catch(done.fail);
}); });
}); });
describe('with u2f available', () => { describe('with u2f available', () => {
beforeEach((done) => { beforeEach(() => {
// bypass automatic form submission within renderAuthenticated // bypass automatic form submission within renderAuthenticated
jest.spyOn(component, 'renderAuthenticated').mockReturnValue(true); jest.spyOn(component, 'renderAuthenticated').mockReturnValue(true);
u2fDevice = new MockU2FDevice(); u2fDevice = new MockU2FDevice();
component.start().then(done).catch(done.fail); return component.start();
}); });
it('allows authenticating via a U2F device', () => { it('allows authenticating via a U2F device', () => {
......
...@@ -8,12 +8,12 @@ describe('U2FRegister', () => { ...@@ -8,12 +8,12 @@ describe('U2FRegister', () => {
let container; let container;
let component; let component;
beforeEach((done) => { beforeEach(() => {
loadFixtures('u2f/register.html'); loadFixtures('u2f/register.html');
u2fDevice = new MockU2FDevice(); u2fDevice = new MockU2FDevice();
container = $('#js-register-token-2fa'); container = $('#js-register-token-2fa');
component = new U2FRegister(container, {}); component = new U2FRegister(container, {});
component.start().then(done).catch(done.fail); return component.start();
}); });
it('allows registering a U2F device', () => { it('allows registering a U2F device', () => {
......
...@@ -38,35 +38,25 @@ describe('AjaxFilter', () => { ...@@ -38,35 +38,25 @@ describe('AjaxFilter', () => {
dummyList.list.appendChild(dynamicList); dummyList.list.appendChild(dynamicList);
}); });
it('calls onLoadingFinished after loading data', (done) => { it('calls onLoadingFinished after loading data', async () => {
ajaxSpy = (url) => { ajaxSpy = (url) => {
expect(url).toBe('dummy endpoint?dummy search key='); expect(url).toBe('dummy endpoint?dummy search key=');
return Promise.resolve(dummyData); return Promise.resolve(dummyData);
}; };
AjaxFilter.trigger() await AjaxFilter.trigger();
.then(() => { expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(1);
expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(1);
})
.then(done)
.catch(done.fail);
}); });
it('does not call onLoadingFinished if Ajax call fails', (done) => { it('does not call onLoadingFinished if Ajax call fails', async () => {
const dummyError = new Error('My dummy is sick! :-('); const dummyError = new Error('My dummy is sick! :-(');
ajaxSpy = (url) => { ajaxSpy = (url) => {
expect(url).toBe('dummy endpoint?dummy search key='); expect(url).toBe('dummy endpoint?dummy search key=');
return Promise.reject(dummyError); return Promise.reject(dummyError);
}; };
AjaxFilter.trigger() await expect(AjaxFilter.trigger()).rejects.toEqual(dummyError);
.then(done.fail) expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(0);
.catch((error) => {
expect(error).toBe(dummyError);
expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(0);
})
.then(done)
.catch(done.fail);
}); });
}); });
}); });
...@@ -190,43 +190,40 @@ describe('Filtered Search Manager', () => { ...@@ -190,43 +190,40 @@ describe('Filtered Search Manager', () => {
const defaultParams = '?scope=all'; const defaultParams = '?scope=all';
const defaultState = '&state=opened'; const defaultState = '&state=opened';
it('should search with a single word', (done) => { it('should search with a single word', () => {
initializeManager(); initializeManager();
input.value = 'searchTerm'; input.value = 'searchTerm';
visitUrl.mockImplementation((url) => { visitUrl.mockImplementation((url) => {
expect(url).toEqual(`${defaultParams}&search=searchTerm`); expect(url).toEqual(`${defaultParams}&search=searchTerm`);
done();
}); });
manager.search(); manager.search();
}); });
it('sets default state', (done) => { it('sets default state', () => {
initializeManager({ useDefaultState: true }); initializeManager({ useDefaultState: true });
input.value = 'searchTerm'; input.value = 'searchTerm';
visitUrl.mockImplementation((url) => { visitUrl.mockImplementation((url) => {
expect(url).toEqual(`${defaultParams}${defaultState}&search=searchTerm`); expect(url).toEqual(`${defaultParams}${defaultState}&search=searchTerm`);
done();
}); });
manager.search(); manager.search();
}); });
it('should search with multiple words', (done) => { it('should search with multiple words', () => {
initializeManager(); initializeManager();
input.value = 'awesome search terms'; input.value = 'awesome search terms';
visitUrl.mockImplementation((url) => { visitUrl.mockImplementation((url) => {
expect(url).toEqual(`${defaultParams}&search=awesome+search+terms`); expect(url).toEqual(`${defaultParams}&search=awesome+search+terms`);
done();
}); });
manager.search(); manager.search();
}); });
it('should search with special characters', (done) => { it('should search with special characters', () => {
initializeManager(); initializeManager();
input.value = '~!@#$%^&*()_+{}:<>,.?/'; input.value = '~!@#$%^&*()_+{}:<>,.?/';
...@@ -234,13 +231,12 @@ describe('Filtered Search Manager', () => { ...@@ -234,13 +231,12 @@ describe('Filtered Search Manager', () => {
expect(url).toEqual( expect(url).toEqual(
`${defaultParams}&search=~!%40%23%24%25%5E%26*()_%2B%7B%7D%3A%3C%3E%2C.%3F%2F`, `${defaultParams}&search=~!%40%23%24%25%5E%26*()_%2B%7B%7D%3A%3C%3E%2C.%3F%2F`,
); );
done();
}); });
manager.search(); manager.search();
}); });
it('should use replacement URL for condition', (done) => { it('should use replacement URL for condition', () => {
initializeManager(); initializeManager();
tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML( tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', '=', '13', true), FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', '=', '13', true),
...@@ -248,7 +244,6 @@ describe('Filtered Search Manager', () => { ...@@ -248,7 +244,6 @@ describe('Filtered Search Manager', () => {
visitUrl.mockImplementation((url) => { visitUrl.mockImplementation((url) => {
expect(url).toEqual(`${defaultParams}&milestone_title=replaced`); expect(url).toEqual(`${defaultParams}&milestone_title=replaced`);
done();
}); });
manager.filteredSearchTokenKeys.conditions.push({ manager.filteredSearchTokenKeys.conditions.push({
...@@ -261,7 +256,7 @@ describe('Filtered Search Manager', () => { ...@@ -261,7 +256,7 @@ describe('Filtered Search Manager', () => {
manager.search(); manager.search();
}); });
it('removes duplicated tokens', (done) => { it('removes duplicated tokens', () => {
initializeManager(); initializeManager();
tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(` tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(`
${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug')} ${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug')}
...@@ -270,7 +265,6 @@ describe('Filtered Search Manager', () => { ...@@ -270,7 +265,6 @@ describe('Filtered Search Manager', () => {
visitUrl.mockImplementation((url) => { visitUrl.mockImplementation((url) => {
expect(url).toEqual(`${defaultParams}&label_name[]=bug`); expect(url).toEqual(`${defaultParams}&label_name[]=bug`);
done();
}); });
manager.search(); manager.search();
......
...@@ -18,53 +18,47 @@ describe('RecentSearchesService', () => { ...@@ -18,53 +18,47 @@ describe('RecentSearchesService', () => {
jest.spyOn(RecentSearchesService, 'isAvailable').mockReturnValue(true); jest.spyOn(RecentSearchesService, 'isAvailable').mockReturnValue(true);
}); });
it('should default to empty array', (done) => { it('should default to empty array', () => {
const fetchItemsPromise = service.fetch(); const fetchItemsPromise = service.fetch();
fetchItemsPromise return fetchItemsPromise.then((items) => {
.then((items) => { expect(items).toEqual([]);
expect(items).toEqual([]); });
})
.then(done)
.catch(done.fail);
}); });
it('should reject when unable to parse', (done) => { it('should reject when unable to parse', () => {
jest.spyOn(localStorage, 'getItem').mockReturnValue('fail'); jest.spyOn(localStorage, 'getItem').mockReturnValue('fail');
const fetchItemsPromise = service.fetch(); const fetchItemsPromise = service.fetch();
fetchItemsPromise return fetchItemsPromise
.then(done.fail) .then(() => {
throw new Error();
})
.catch((error) => { .catch((error) => {
expect(error).toEqual(expect.any(SyntaxError)); expect(error).toEqual(expect.any(SyntaxError));
}) });
.then(done)
.catch(done.fail);
}); });
it('should reject when service is unavailable', (done) => { it('should reject when service is unavailable', () => {
RecentSearchesService.isAvailable.mockReturnValue(false); RecentSearchesService.isAvailable.mockReturnValue(false);
service return service
.fetch() .fetch()
.then(done.fail) .then(() => {
throw new Error();
})
.catch((error) => { .catch((error) => {
expect(error).toEqual(expect.any(Error)); expect(error).toEqual(expect.any(Error));
}) });
.then(done)
.catch(done.fail);
}); });
it('should return items from localStorage', (done) => { it('should return items from localStorage', () => {
jest.spyOn(localStorage, 'getItem').mockReturnValue('["foo", "bar"]'); jest.spyOn(localStorage, 'getItem').mockReturnValue('["foo", "bar"]');
const fetchItemsPromise = service.fetch(); const fetchItemsPromise = service.fetch();
fetchItemsPromise return fetchItemsPromise.then((items) => {
.then((items) => { expect(items).toEqual(['foo', 'bar']);
expect(items).toEqual(['foo', 'bar']); });
})
.then(done)
.catch(done.fail);
}); });
describe('if .isAvailable returns `false`', () => { describe('if .isAvailable returns `false`', () => {
...@@ -74,16 +68,16 @@ describe('RecentSearchesService', () => { ...@@ -74,16 +68,16 @@ describe('RecentSearchesService', () => {
jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {}); jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {});
}); });
it('should not call .getItem', (done) => { it('should not call .getItem', () => {
RecentSearchesService.prototype return RecentSearchesService.prototype
.fetch() .fetch()
.then(done.fail) .then(() => {
throw new Error();
})
.catch((err) => { .catch((err) => {
expect(err).toEqual(new RecentSearchesServiceError()); expect(err).toEqual(new RecentSearchesServiceError());
expect(localStorage.getItem).not.toHaveBeenCalled(); expect(localStorage.getItem).not.toHaveBeenCalled();
}) });
.then(done)
.catch(done.fail);
}); });
}); });
}); });
......
...@@ -46,7 +46,7 @@ describe('Filtered Search Visual Tokens', () => { ...@@ -46,7 +46,7 @@ describe('Filtered Search Visual Tokens', () => {
jest.spyOn(UsersCache, 'retrieve').mockImplementation((username) => usersCacheSpy(username)); jest.spyOn(UsersCache, 'retrieve').mockImplementation((username) => usersCacheSpy(username));
}); });
it('ignores error if UsersCache throws', (done) => { it('ignores error if UsersCache throws', async () => {
const dummyError = new Error('Earth rotated backwards'); const dummyError = new Error('Earth rotated backwards');
const { subject, tokenValueContainer, tokenValueElement } = findElements(authorToken); const { subject, tokenValueContainer, tokenValueElement } = findElements(authorToken);
const tokenValue = tokenValueElement.innerText; const tokenValue = tokenValueElement.innerText;
...@@ -55,16 +55,11 @@ describe('Filtered Search Visual Tokens', () => { ...@@ -55,16 +55,11 @@ describe('Filtered Search Visual Tokens', () => {
return Promise.reject(dummyError); return Promise.reject(dummyError);
}; };
subject await subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue);
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue) expect(createFlash.mock.calls.length).toBe(0);
.then(() => {
expect(createFlash.mock.calls.length).toBe(0);
})
.then(done)
.catch(done.fail);
}); });
it('does nothing if user cannot be found', (done) => { it('does nothing if user cannot be found', async () => {
const { subject, tokenValueContainer, tokenValueElement } = findElements(authorToken); const { subject, tokenValueContainer, tokenValueElement } = findElements(authorToken);
const tokenValue = tokenValueElement.innerText; const tokenValue = tokenValueElement.innerText;
usersCacheSpy = (username) => { usersCacheSpy = (username) => {
...@@ -72,16 +67,11 @@ describe('Filtered Search Visual Tokens', () => { ...@@ -72,16 +67,11 @@ describe('Filtered Search Visual Tokens', () => {
return Promise.resolve(undefined); return Promise.resolve(undefined);
}; };
subject await subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue);
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue) expect(tokenValueElement.innerText).toBe(tokenValue);
.then(() => {
expect(tokenValueElement.innerText).toBe(tokenValue);
})
.then(done)
.catch(done.fail);
}); });
it('replaces author token with avatar and display name', (done) => { it('replaces author token with avatar and display name', async () => {
const dummyUser = { const dummyUser = {
name: 'Important Person', name: 'Important Person',
avatar_url: 'https://host.invalid/mypics/avatar.png', avatar_url: 'https://host.invalid/mypics/avatar.png',
...@@ -93,21 +83,16 @@ describe('Filtered Search Visual Tokens', () => { ...@@ -93,21 +83,16 @@ describe('Filtered Search Visual Tokens', () => {
return Promise.resolve(dummyUser); return Promise.resolve(dummyUser);
}; };
subject await subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue);
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue) expect(tokenValueContainer.dataset.originalValue).toBe(tokenValue);
.then(() => { expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
expect(tokenValueContainer.dataset.originalValue).toBe(tokenValue); const avatar = tokenValueElement.querySelector('img.avatar');
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
const avatar = tokenValueElement.querySelector('img.avatar'); expect(avatar.getAttribute('src')).toBe(dummyUser.avatar_url);
expect(avatar.getAttribute('alt')).toBe('');
expect(avatar.getAttribute('src')).toBe(dummyUser.avatar_url);
expect(avatar.getAttribute('alt')).toBe('');
})
.then(done)
.catch(done.fail);
}); });
it('escapes user name when creating token', (done) => { it('escapes user name when creating token', async () => {
const dummyUser = { const dummyUser = {
name: '<script>', name: '<script>',
avatar_url: `${TEST_HOST}/mypics/avatar.png`, avatar_url: `${TEST_HOST}/mypics/avatar.png`,
...@@ -119,16 +104,11 @@ describe('Filtered Search Visual Tokens', () => { ...@@ -119,16 +104,11 @@ describe('Filtered Search Visual Tokens', () => {
return Promise.resolve(dummyUser); return Promise.resolve(dummyUser);
}; };
subject await subject.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue);
.updateUserTokenAppearance(tokenValueContainer, tokenValueElement, tokenValue) expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
.then(() => { tokenValueElement.querySelector('.avatar').remove();
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
tokenValueElement.querySelector('.avatar').remove();
expect(tokenValueElement.innerHTML.trim()).toBe(escape(dummyUser.name)); expect(tokenValueElement.innerHTML.trim()).toBe(escape(dummyUser.name));
})
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -177,48 +157,33 @@ describe('Filtered Search Visual Tokens', () => { ...@@ -177,48 +157,33 @@ describe('Filtered Search Visual Tokens', () => {
const findLabel = (tokenValue) => const findLabel = (tokenValue) =>
labelData.find((label) => tokenValue === `~${DropdownUtils.getEscapedText(label.title)}`); labelData.find((label) => tokenValue === `~${DropdownUtils.getEscapedText(label.title)}`);
it('updates the color of a label token', (done) => { it('updates the color of a label token', async () => {
const { subject, tokenValueContainer, tokenValueElement } = findElements(bugLabelToken); const { subject, tokenValueContainer, tokenValueElement } = findElements(bugLabelToken);
const tokenValue = tokenValueElement.innerText; const tokenValue = tokenValueElement.innerText;
const matchingLabel = findLabel(tokenValue); const matchingLabel = findLabel(tokenValue);
subject await subject.updateLabelTokenColor(tokenValueContainer, tokenValue);
.updateLabelTokenColor(tokenValueContainer, tokenValue) expectValueContainerStyle(tokenValueContainer, matchingLabel);
.then(() => {
expectValueContainerStyle(tokenValueContainer, matchingLabel);
})
.then(done)
.catch(done.fail);
}); });
it('updates the color of a label token with spaces', (done) => { it('updates the color of a label token with spaces', async () => {
const { subject, tokenValueContainer, tokenValueElement } = findElements(spaceLabelToken); const { subject, tokenValueContainer, tokenValueElement } = findElements(spaceLabelToken);
const tokenValue = tokenValueElement.innerText; const tokenValue = tokenValueElement.innerText;
const matchingLabel = findLabel(tokenValue); const matchingLabel = findLabel(tokenValue);
subject await subject.updateLabelTokenColor(tokenValueContainer, tokenValue);
.updateLabelTokenColor(tokenValueContainer, tokenValue) expectValueContainerStyle(tokenValueContainer, matchingLabel);
.then(() => {
expectValueContainerStyle(tokenValueContainer, matchingLabel);
})
.then(done)
.catch(done.fail);
}); });
it('does not change color of a missing label', (done) => { it('does not change color of a missing label', async () => {
const { subject, tokenValueContainer, tokenValueElement } = findElements(missingLabelToken); const { subject, tokenValueContainer, tokenValueElement } = findElements(missingLabelToken);
const tokenValue = tokenValueElement.innerText; const tokenValue = tokenValueElement.innerText;
const matchingLabel = findLabel(tokenValue); const matchingLabel = findLabel(tokenValue);
expect(matchingLabel).toBe(undefined); expect(matchingLabel).toBe(undefined);
subject await subject.updateLabelTokenColor(tokenValueContainer, tokenValue);
.updateLabelTokenColor(tokenValueContainer, tokenValue) expect(tokenValueContainer.getAttribute('style')).toBe(null);
.then(() => {
expect(tokenValueContainer.getAttribute('style')).toBe(null);
})
.then(done)
.catch(done.fail);
}); });
}); });
......
...@@ -29,136 +29,126 @@ describe('Frequent Items Dropdown Store Actions', () => { ...@@ -29,136 +29,126 @@ describe('Frequent Items Dropdown Store Actions', () => {
}); });
describe('setNamespace', () => { describe('setNamespace', () => {
it('should set namespace', (done) => { it('should set namespace', () => {
testAction( return testAction(
actions.setNamespace, actions.setNamespace,
mockNamespace, mockNamespace,
mockedState, mockedState,
[{ type: types.SET_NAMESPACE, payload: mockNamespace }], [{ type: types.SET_NAMESPACE, payload: mockNamespace }],
[], [],
done,
); );
}); });
}); });
describe('setStorageKey', () => { describe('setStorageKey', () => {
it('should set storage key', (done) => { it('should set storage key', () => {
testAction( return testAction(
actions.setStorageKey, actions.setStorageKey,
mockStorageKey, mockStorageKey,
mockedState, mockedState,
[{ type: types.SET_STORAGE_KEY, payload: mockStorageKey }], [{ type: types.SET_STORAGE_KEY, payload: mockStorageKey }],
[], [],
done,
); );
}); });
}); });
describe('requestFrequentItems', () => { describe('requestFrequentItems', () => {
it('should request frequent items', (done) => { it('should request frequent items', () => {
testAction( return testAction(
actions.requestFrequentItems, actions.requestFrequentItems,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_FREQUENT_ITEMS }], [{ type: types.REQUEST_FREQUENT_ITEMS }],
[], [],
done,
); );
}); });
}); });
describe('receiveFrequentItemsSuccess', () => { describe('receiveFrequentItemsSuccess', () => {
it('should set frequent items', (done) => { it('should set frequent items', () => {
testAction( return testAction(
actions.receiveFrequentItemsSuccess, actions.receiveFrequentItemsSuccess,
mockFrequentProjects, mockFrequentProjects,
mockedState, mockedState,
[{ type: types.RECEIVE_FREQUENT_ITEMS_SUCCESS, payload: mockFrequentProjects }], [{ type: types.RECEIVE_FREQUENT_ITEMS_SUCCESS, payload: mockFrequentProjects }],
[], [],
done,
); );
}); });
}); });
describe('receiveFrequentItemsError', () => { describe('receiveFrequentItemsError', () => {
it('should set frequent items error state', (done) => { it('should set frequent items error state', () => {
testAction( return testAction(
actions.receiveFrequentItemsError, actions.receiveFrequentItemsError,
null, null,
mockedState, mockedState,
[{ type: types.RECEIVE_FREQUENT_ITEMS_ERROR }], [{ type: types.RECEIVE_FREQUENT_ITEMS_ERROR }],
[], [],
done,
); );
}); });
}); });
describe('fetchFrequentItems', () => { describe('fetchFrequentItems', () => {
it('should dispatch `receiveFrequentItemsSuccess`', (done) => { it('should dispatch `receiveFrequentItemsSuccess`', () => {
mockedState.namespace = mockNamespace; mockedState.namespace = mockNamespace;
mockedState.storageKey = mockStorageKey; mockedState.storageKey = mockStorageKey;
testAction( return testAction(
actions.fetchFrequentItems, actions.fetchFrequentItems,
null, null,
mockedState, mockedState,
[], [],
[{ type: 'requestFrequentItems' }, { type: 'receiveFrequentItemsSuccess', payload: [] }], [{ type: 'requestFrequentItems' }, { type: 'receiveFrequentItemsSuccess', payload: [] }],
done,
); );
}); });
it('should dispatch `receiveFrequentItemsError`', (done) => { it('should dispatch `receiveFrequentItemsError`', () => {
jest.spyOn(AccessorUtilities, 'canUseLocalStorage').mockReturnValue(false); jest.spyOn(AccessorUtilities, 'canUseLocalStorage').mockReturnValue(false);
mockedState.namespace = mockNamespace; mockedState.namespace = mockNamespace;
mockedState.storageKey = mockStorageKey; mockedState.storageKey = mockStorageKey;
testAction( return testAction(
actions.fetchFrequentItems, actions.fetchFrequentItems,
null, null,
mockedState, mockedState,
[], [],
[{ type: 'requestFrequentItems' }, { type: 'receiveFrequentItemsError' }], [{ type: 'requestFrequentItems' }, { type: 'receiveFrequentItemsError' }],
done,
); );
}); });
}); });
describe('requestSearchedItems', () => { describe('requestSearchedItems', () => {
it('should request searched items', (done) => { it('should request searched items', () => {
testAction( return testAction(
actions.requestSearchedItems, actions.requestSearchedItems,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_SEARCHED_ITEMS }], [{ type: types.REQUEST_SEARCHED_ITEMS }],
[], [],
done,
); );
}); });
}); });
describe('receiveSearchedItemsSuccess', () => { describe('receiveSearchedItemsSuccess', () => {
it('should set searched items', (done) => { it('should set searched items', () => {
testAction( return testAction(
actions.receiveSearchedItemsSuccess, actions.receiveSearchedItemsSuccess,
mockSearchedProjects, mockSearchedProjects,
mockedState, mockedState,
[{ type: types.RECEIVE_SEARCHED_ITEMS_SUCCESS, payload: mockSearchedProjects }], [{ type: types.RECEIVE_SEARCHED_ITEMS_SUCCESS, payload: mockSearchedProjects }],
[], [],
done,
); );
}); });
}); });
describe('receiveSearchedItemsError', () => { describe('receiveSearchedItemsError', () => {
it('should set searched items error state', (done) => { it('should set searched items error state', () => {
testAction( return testAction(
actions.receiveSearchedItemsError, actions.receiveSearchedItemsError,
null, null,
mockedState, mockedState,
[{ type: types.RECEIVE_SEARCHED_ITEMS_ERROR }], [{ type: types.RECEIVE_SEARCHED_ITEMS_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -168,10 +158,10 @@ describe('Frequent Items Dropdown Store Actions', () => { ...@@ -168,10 +158,10 @@ describe('Frequent Items Dropdown Store Actions', () => {
gon.api_version = 'v4'; gon.api_version = 'v4';
}); });
it('should dispatch `receiveSearchedItemsSuccess`', (done) => { it('should dispatch `receiveSearchedItemsSuccess`', () => {
mock.onGet(/\/api\/v4\/projects.json(.*)$/).replyOnce(200, mockSearchedProjects, {}); mock.onGet(/\/api\/v4\/projects.json(.*)$/).replyOnce(200, mockSearchedProjects, {});
testAction( return testAction(
actions.fetchSearchedItems, actions.fetchSearchedItems,
null, null,
mockedState, mockedState,
...@@ -183,45 +173,41 @@ describe('Frequent Items Dropdown Store Actions', () => { ...@@ -183,45 +173,41 @@ describe('Frequent Items Dropdown Store Actions', () => {
payload: { data: mockSearchedProjects, headers: {} }, payload: { data: mockSearchedProjects, headers: {} },
}, },
], ],
done,
); );
}); });
it('should dispatch `receiveSearchedItemsError`', (done) => { it('should dispatch `receiveSearchedItemsError`', () => {
gon.api_version = 'v4'; gon.api_version = 'v4';
mock.onGet(/\/api\/v4\/projects.json(.*)$/).replyOnce(500); mock.onGet(/\/api\/v4\/projects.json(.*)$/).replyOnce(500);
testAction( return testAction(
actions.fetchSearchedItems, actions.fetchSearchedItems,
null, null,
mockedState, mockedState,
[], [],
[{ type: 'requestSearchedItems' }, { type: 'receiveSearchedItemsError' }], [{ type: 'requestSearchedItems' }, { type: 'receiveSearchedItemsError' }],
done,
); );
}); });
}); });
describe('setSearchQuery', () => { describe('setSearchQuery', () => {
it('should commit query and dispatch `fetchSearchedItems` when query is present', (done) => { it('should commit query and dispatch `fetchSearchedItems` when query is present', () => {
testAction( return testAction(
actions.setSearchQuery, actions.setSearchQuery,
{ query: 'test' }, { query: 'test' },
mockedState, mockedState,
[{ type: types.SET_SEARCH_QUERY, payload: { query: 'test' } }], [{ type: types.SET_SEARCH_QUERY, payload: { query: 'test' } }],
[{ type: 'fetchSearchedItems', payload: { query: 'test' } }], [{ type: 'fetchSearchedItems', payload: { query: 'test' } }],
done,
); );
}); });
it('should commit query and dispatch `fetchFrequentItems` when query is empty', (done) => { it('should commit query and dispatch `fetchFrequentItems` when query is empty', () => {
testAction( return testAction(
actions.setSearchQuery, actions.setSearchQuery,
null, null,
mockedState, mockedState,
[{ type: types.SET_SEARCH_QUERY, payload: null }], [{ type: types.SET_SEARCH_QUERY, payload: null }],
[{ type: 'fetchFrequentItems' }], [{ type: 'fetchFrequentItems' }],
done,
); );
}); });
}); });
......
...@@ -11,23 +11,21 @@ describe('initDiscussionTab', () => { ...@@ -11,23 +11,21 @@ describe('initDiscussionTab', () => {
`); `);
}); });
it('should pass canCreateNote as false to initImageDiff', (done) => { it('should pass canCreateNote as false to initImageDiff', () => {
jest jest
.spyOn(initImageDiffHelper, 'initImageDiff') .spyOn(initImageDiffHelper, 'initImageDiff')
.mockImplementation((diffFileEl, canCreateNote) => { .mockImplementation((diffFileEl, canCreateNote) => {
expect(canCreateNote).toEqual(false); expect(canCreateNote).toEqual(false);
done();
}); });
initDiscussionTab(); initDiscussionTab();
}); });
it('should pass renderCommentBadge as true to initImageDiff', (done) => { it('should pass renderCommentBadge as true to initImageDiff', () => {
jest jest
.spyOn(initImageDiffHelper, 'initImageDiff') .spyOn(initImageDiffHelper, 'initImageDiff')
.mockImplementation((diffFileEl, canCreateNote, renderCommentBadge) => { .mockImplementation((diffFileEl, canCreateNote, renderCommentBadge) => {
expect(renderCommentBadge).toEqual(true); expect(renderCommentBadge).toEqual(true);
done();
}); });
initDiscussionTab(); initDiscussionTab();
......
...@@ -176,34 +176,36 @@ describe('ReplacedImageDiff', () => { ...@@ -176,34 +176,36 @@ describe('ReplacedImageDiff', () => {
expect(ImageDiff.prototype.bindEvents).toHaveBeenCalled(); expect(ImageDiff.prototype.bindEvents).toHaveBeenCalled();
}); });
it('should register click eventlistener to 2-up view mode', (done) => { it('should register click eventlistener to 2-up view mode', () => {
jest.spyOn(ReplacedImageDiff.prototype, 'changeView').mockImplementation((viewMode) => { const changeViewSpy = jest
expect(viewMode).toEqual(viewTypes.TWO_UP); .spyOn(ReplacedImageDiff.prototype, 'changeView')
done(); .mockImplementation(() => {});
});
replacedImageDiff.bindEvents(); replacedImageDiff.bindEvents();
replacedImageDiff.viewModesEls[viewTypes.TWO_UP].click(); replacedImageDiff.viewModesEls[viewTypes.TWO_UP].click();
expect(changeViewSpy).toHaveBeenCalledWith(viewTypes.TWO_UP, expect.any(Object));
}); });
it('should register click eventlistener to swipe view mode', (done) => { it('should register click eventlistener to swipe view mode', () => {
jest.spyOn(ReplacedImageDiff.prototype, 'changeView').mockImplementation((viewMode) => { const changeViewSpy = jest
expect(viewMode).toEqual(viewTypes.SWIPE); .spyOn(ReplacedImageDiff.prototype, 'changeView')
done(); .mockImplementation(() => {});
});
replacedImageDiff.bindEvents(); replacedImageDiff.bindEvents();
replacedImageDiff.viewModesEls[viewTypes.SWIPE].click(); replacedImageDiff.viewModesEls[viewTypes.SWIPE].click();
expect(changeViewSpy).toHaveBeenCalledWith(viewTypes.SWIPE, expect.any(Object));
}); });
it('should register click eventlistener to onion skin view mode', (done) => { it('should register click eventlistener to onion skin view mode', () => {
jest.spyOn(ReplacedImageDiff.prototype, 'changeView').mockImplementation((viewMode) => { const changeViewSpy = jest
expect(viewMode).toEqual(viewTypes.SWIPE); .spyOn(ReplacedImageDiff.prototype, 'changeView')
done(); .mockImplementation(() => {});
});
replacedImageDiff.bindEvents(); replacedImageDiff.bindEvents();
replacedImageDiff.viewModesEls[viewTypes.SWIPE].click(); replacedImageDiff.viewModesEls[viewTypes.SWIPE].click();
expect(changeViewSpy).toHaveBeenCalledWith(viewTypes.SWIPE, expect.any(Object));
}); });
}); });
...@@ -325,32 +327,34 @@ describe('ReplacedImageDiff', () => { ...@@ -325,32 +327,34 @@ describe('ReplacedImageDiff', () => {
setupImageFrameEls(); setupImageFrameEls();
}); });
it('should pass showCommentIndicator normalized indicator values', (done) => { it('should pass showCommentIndicator normalized indicator values', () => {
jest.spyOn(imageDiffHelper, 'showCommentIndicator').mockImplementation(() => {}); jest.spyOn(imageDiffHelper, 'showCommentIndicator').mockImplementation(() => {});
jest const resizeCoordinatesToImageElementSpy = jest
.spyOn(imageDiffHelper, 'resizeCoordinatesToImageElement') .spyOn(imageDiffHelper, 'resizeCoordinatesToImageElement')
.mockImplementation((imageEl, meta) => { .mockImplementation(() => {});
expect(meta.x).toEqual(indicator.x);
expect(meta.y).toEqual(indicator.y);
expect(meta.width).toEqual(indicator.image.width);
expect(meta.height).toEqual(indicator.image.height);
done();
});
replacedImageDiff.renderNewView(indicator); replacedImageDiff.renderNewView(indicator);
expect(resizeCoordinatesToImageElementSpy).toHaveBeenCalledWith(undefined, {
x: indicator.x,
y: indicator.y,
width: indicator.image.width,
height: indicator.image.height,
});
}); });
it('should call showCommentIndicator', (done) => { it('should call showCommentIndicator', () => {
const normalized = { const normalized = {
normalized: true, normalized: true,
}; };
jest.spyOn(imageDiffHelper, 'resizeCoordinatesToImageElement').mockReturnValue(normalized); jest.spyOn(imageDiffHelper, 'resizeCoordinatesToImageElement').mockReturnValue(normalized);
jest const showCommentIndicatorSpy = jest
.spyOn(imageDiffHelper, 'showCommentIndicator') .spyOn(imageDiffHelper, 'showCommentIndicator')
.mockImplementation((imageFrameEl, normalizedIndicator) => { .mockImplementation(() => {});
expect(normalizedIndicator).toEqual(normalized);
done();
});
replacedImageDiff.renderNewView(indicator); replacedImageDiff.renderNewView(indicator);
expect(showCommentIndicatorSpy).toHaveBeenCalledWith(undefined, normalized);
}); });
}); });
}); });
......
...@@ -38,21 +38,16 @@ describe('CreateMergeRequestDropdown', () => { ...@@ -38,21 +38,16 @@ describe('CreateMergeRequestDropdown', () => {
}); });
describe('getRef', () => { describe('getRef', () => {
it('escapes branch names correctly', (done) => { it('escapes branch names correctly', async () => {
const endpoint = `${dropdown.refsPath}contains%23hash`; const endpoint = `${dropdown.refsPath}contains%23hash`;
jest.spyOn(axios, 'get'); jest.spyOn(axios, 'get');
axiosMock.onGet(endpoint).replyOnce({}); axiosMock.onGet(endpoint).replyOnce({});
dropdown await dropdown.getRef('contains#hash');
.getRef('contains#hash') expect(axios.get).toHaveBeenCalledWith(
.then(() => { endpoint,
expect(axios.get).toHaveBeenCalledWith( expect.objectContaining({ cancelToken: expect.anything() }),
endpoint, );
expect.objectContaining({ cancelToken: expect.anything() }),
);
})
.then(done)
.catch(done.fail);
}); });
}); });
......
...@@ -23,90 +23,82 @@ describe('RelatedMergeRequest store actions', () => { ...@@ -23,90 +23,82 @@ describe('RelatedMergeRequest store actions', () => {
}); });
describe('setInitialState', () => { describe('setInitialState', () => {
it('commits types.SET_INITIAL_STATE with given props', (done) => { it('commits types.SET_INITIAL_STATE with given props', () => {
const props = { a: 1, b: 2 }; const props = { a: 1, b: 2 };
testAction( return testAction(
actions.setInitialState, actions.setInitialState,
props, props,
{}, {},
[{ type: types.SET_INITIAL_STATE, payload: props }], [{ type: types.SET_INITIAL_STATE, payload: props }],
[], [],
done,
); );
}); });
}); });
describe('requestData', () => { describe('requestData', () => {
it('commits types.REQUEST_DATA', (done) => { it('commits types.REQUEST_DATA', () => {
testAction(actions.requestData, null, {}, [{ type: types.REQUEST_DATA }], [], done); return testAction(actions.requestData, null, {}, [{ type: types.REQUEST_DATA }], []);
}); });
}); });
describe('receiveDataSuccess', () => { describe('receiveDataSuccess', () => {
it('commits types.RECEIVE_DATA_SUCCESS with data', (done) => { it('commits types.RECEIVE_DATA_SUCCESS with data', () => {
const data = { a: 1, b: 2 }; const data = { a: 1, b: 2 };
testAction( return testAction(
actions.receiveDataSuccess, actions.receiveDataSuccess,
data, data,
{}, {},
[{ type: types.RECEIVE_DATA_SUCCESS, payload: data }], [{ type: types.RECEIVE_DATA_SUCCESS, payload: data }],
[], [],
done,
); );
}); });
}); });
describe('receiveDataError', () => { describe('receiveDataError', () => {
it('commits types.RECEIVE_DATA_ERROR', (done) => { it('commits types.RECEIVE_DATA_ERROR', () => {
testAction( return testAction(
actions.receiveDataError, actions.receiveDataError,
null, null,
{}, {},
[{ type: types.RECEIVE_DATA_ERROR }], [{ type: types.RECEIVE_DATA_ERROR }],
[], [],
done,
); );
}); });
}); });
describe('fetchMergeRequests', () => { describe('fetchMergeRequests', () => {
describe('for a successful request', () => { describe('for a successful request', () => {
it('should dispatch success action', (done) => { it('should dispatch success action', () => {
const data = { a: 1 }; const data = { a: 1 };
mock.onGet(`${state.apiEndpoint}?per_page=100`).replyOnce(200, data, { 'x-total': 2 }); mock.onGet(`${state.apiEndpoint}?per_page=100`).replyOnce(200, data, { 'x-total': 2 });
testAction( return testAction(
actions.fetchMergeRequests, actions.fetchMergeRequests,
null, null,
state, state,
[], [],
[{ type: 'requestData' }, { type: 'receiveDataSuccess', payload: { data, total: 2 } }], [{ type: 'requestData' }, { type: 'receiveDataSuccess', payload: { data, total: 2 } }],
done,
); );
}); });
}); });
describe('for a failing request', () => { describe('for a failing request', () => {
it('should dispatch error action', (done) => { it('should dispatch error action', async () => {
mock.onGet(`${state.apiEndpoint}?per_page=100`).replyOnce(400); mock.onGet(`${state.apiEndpoint}?per_page=100`).replyOnce(400);
testAction( await testAction(
actions.fetchMergeRequests, actions.fetchMergeRequests,
null, null,
state, state,
[], [],
[{ type: 'requestData' }, { type: 'receiveDataError' }], [{ type: 'requestData' }, { type: 'receiveDataError' }],
() => {
expect(createFlash).toHaveBeenCalledTimes(1);
expect(createFlash).toHaveBeenCalledWith({
message: expect.stringMatching('Something went wrong'),
});
done();
},
); );
expect(createFlash).toHaveBeenCalledTimes(1);
expect(createFlash).toHaveBeenCalledWith({
message: expect.stringMatching('Something went wrong'),
});
}); });
}); });
}); });
......
...@@ -375,8 +375,8 @@ describe('Job App', () => { ...@@ -375,8 +375,8 @@ describe('Job App', () => {
}); });
describe('sidebar', () => { describe('sidebar', () => {
it('has no blank blocks', (done) => { it('has no blank blocks', async () => {
setupAndMount({ await setupAndMount({
jobData: { jobData: {
duration: null, duration: null,
finished_at: null, finished_at: null,
...@@ -387,17 +387,14 @@ describe('Job App', () => { ...@@ -387,17 +387,14 @@ describe('Job App', () => {
tags: [], tags: [],
cancel_path: null, cancel_path: null,
}, },
}) });
.then(() => {
const blocks = wrapper.findAll('.blocks-container > *').wrappers; const blocks = wrapper.findAll('.blocks-container > *').wrappers;
expect(blocks.length).toBeGreaterThan(0); expect(blocks.length).toBeGreaterThan(0);
blocks.forEach((block) => { blocks.forEach((block) => {
expect(block.text().trim()).not.toBe(''); expect(block.text().trim()).not.toBe('');
}); });
})
.then(done)
.catch(done.fail);
}); });
}); });
}); });
......
This diff is collapsed.
...@@ -50,7 +50,7 @@ describe('Promote label modal', () => { ...@@ -50,7 +50,7 @@ describe('Promote label modal', () => {
vm.$destroy(); vm.$destroy();
}); });
it('redirects when a label is promoted', (done) => { it('redirects when a label is promoted', () => {
const responseURL = `${TEST_HOST}/dummy/endpoint`; const responseURL = `${TEST_HOST}/dummy/endpoint`;
jest.spyOn(axios, 'post').mockImplementation((url) => { jest.spyOn(axios, 'post').mockImplementation((url) => {
expect(url).toBe(labelMockData.url); expect(url).toBe(labelMockData.url);
...@@ -65,39 +65,35 @@ describe('Promote label modal', () => { ...@@ -65,39 +65,35 @@ describe('Promote label modal', () => {
}); });
}); });
vm.onSubmit() return vm.onSubmit().then(() => {
.then(() => { expect(eventHub.$emit).toHaveBeenCalledWith('promoteLabelModal.requestFinished', {
expect(eventHub.$emit).toHaveBeenCalledWith('promoteLabelModal.requestFinished', { labelUrl: labelMockData.url,
labelUrl: labelMockData.url, successful: true,
successful: true, });
}); });
})
.then(done)
.catch(done.fail);
}); });
it('displays an error if promoting a label failed', (done) => { it('displays an error if promoting a label failed', () => {
const dummyError = new Error('promoting label failed'); const dummyError = new Error('promoting label failed');
dummyError.response = { status: 500 }; dummyError.response = { status: 500 };
jest.spyOn(axios, 'post').mockImplementation((url) => { jest.spyOn(axios, 'post').mockImplementation((url) => {
expect(url).toBe(labelMockData.url); expect(url).toBe(labelMockData.url);
expect(eventHub.$emit).toHaveBeenCalledWith( expect(eventHub.$emit).toHaveBeenCalledWith(
'promoteLabelModal.requestStarted', 'promoteLabelModal.requestStarted',
labelMockData.url, labelMockData.url,
); );
return Promise.reject(dummyError); return Promise.reject(dummyError);
}); });
vm.onSubmit() return vm.onSubmit().catch((error) => {
.catch((error) => { expect(error).toBe(dummyError);
expect(error).toBe(dummyError); expect(eventHub.$emit).toHaveBeenCalledWith('promoteLabelModal.requestFinished', {
expect(eventHub.$emit).toHaveBeenCalledWith('promoteLabelModal.requestFinished', { labelUrl: labelMockData.url,
labelUrl: labelMockData.url, successful: false,
successful: false, });
}); });
})
.then(done)
.catch(done.fail);
}); });
}); });
}); });
...@@ -82,34 +82,39 @@ describe('getSuppressNetworkErrorsDuringNavigationLink', () => { ...@@ -82,34 +82,39 @@ describe('getSuppressNetworkErrorsDuringNavigationLink', () => {
isNavigatingAway.mockReturnValue(false); isNavigatingAway.mockReturnValue(false);
}); });
it('forwards successful requests', (done) => { it('forwards successful requests', () => {
createSubscription(makeMockSuccessLink(), { createSubscription(makeMockSuccessLink(), {
next({ data }) { next({ data }) {
expect(data).toEqual({ foo: { id: 1 } }); expect(data).toEqual({ foo: { id: 1 } });
}, },
error: () => done.fail('Should not happen'), error: () => {
complete: () => done(), throw new Error('Should not happen');
},
}); });
}); });
it('forwards GraphQL errors', (done) => { it('forwards GraphQL errors', () => {
createSubscription(makeMockGraphQLErrorLink(), { createSubscription(makeMockGraphQLErrorLink(), {
next({ errors }) { next({ errors }) {
expect(errors).toEqual([{ message: 'foo' }]); expect(errors).toEqual([{ message: 'foo' }]);
}, },
error: () => done.fail('Should not happen'), error: () => {
complete: () => done(), throw new Error('Should not happen');
},
}); });
}); });
it('forwards network errors', (done) => { it('forwards network errors', () => {
createSubscription(makeMockNetworkErrorLink(), { createSubscription(makeMockNetworkErrorLink(), {
next: () => done.fail('Should not happen'), next: () => {
throw new Error('Should not happen');
},
error: (error) => { error: (error) => {
expect(error.message).toBe('NetworkError'); expect(error.message).toBe('NetworkError');
done();
}, },
complete: () => done.fail('Should not happen'), complete: () => {
throw new Error('Should not happen');
},
}); });
}); });
}); });
...@@ -119,23 +124,25 @@ describe('getSuppressNetworkErrorsDuringNavigationLink', () => { ...@@ -119,23 +124,25 @@ describe('getSuppressNetworkErrorsDuringNavigationLink', () => {
isNavigatingAway.mockReturnValue(true); isNavigatingAway.mockReturnValue(true);
}); });
it('forwards successful requests', (done) => { it('forwards successful requests', () => {
createSubscription(makeMockSuccessLink(), { createSubscription(makeMockSuccessLink(), {
next({ data }) { next({ data }) {
expect(data).toEqual({ foo: { id: 1 } }); expect(data).toEqual({ foo: { id: 1 } });
}, },
error: () => done.fail('Should not happen'), error: () => {
complete: () => done(), throw new Error('Should not happen');
},
}); });
}); });
it('forwards GraphQL errors', (done) => { it('forwards GraphQL errors', () => {
createSubscription(makeMockGraphQLErrorLink(), { createSubscription(makeMockGraphQLErrorLink(), {
next({ errors }) { next({ errors }) {
expect(errors).toEqual([{ message: 'foo' }]); expect(errors).toEqual([{ message: 'foo' }]);
}, },
error: () => done.fail('Should not happen'), error: () => {
complete: () => done(), throw new Error('Should not happen');
},
}); });
}); });
}); });
......
...@@ -58,17 +58,16 @@ describe('StartupJSLink', () => { ...@@ -58,17 +58,16 @@ describe('StartupJSLink', () => {
link = ApolloLink.from([startupLink, new ApolloLink(() => Observable.of(FORWARDED_RESPONSE))]); link = ApolloLink.from([startupLink, new ApolloLink(() => Observable.of(FORWARDED_RESPONSE))]);
}; };
it('forwards requests if no calls are set up', (done) => { it('forwards requests if no calls are set up', () => {
setupLink(); setupLink();
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls).toBe(null); expect(startupLink.startupCalls).toBe(null);
expect(startupLink.request).toEqual(StartupJSLink.noopRequest); expect(startupLink.request).toEqual(StartupJSLink.noopRequest);
done();
}); });
}); });
it('forwards requests if the operation is not pre-loaded', (done) => { it('forwards requests if the operation is not pre-loaded', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -82,12 +81,11 @@ describe('StartupJSLink', () => { ...@@ -82,12 +81,11 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ operationName: 'notLoaded' })).subscribe((result) => { link.request(mockOperation({ operationName: 'notLoaded' })).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(1); expect(startupLink.startupCalls.size).toBe(1);
done();
}); });
}); });
describe('variable match errors: ', () => { describe('variable match errors: ', () => {
it('forwards requests if the variables are not matching', (done) => { it('forwards requests if the variables are not matching', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -101,11 +99,10 @@ describe('StartupJSLink', () => { ...@@ -101,11 +99,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('forwards requests if more variables are set in the operation', (done) => { it('forwards requests if more variables are set in the operation', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -118,11 +115,10 @@ describe('StartupJSLink', () => { ...@@ -118,11 +115,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('forwards requests if less variables are set in the operation', (done) => { it('forwards requests if less variables are set in the operation', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -136,11 +132,10 @@ describe('StartupJSLink', () => { ...@@ -136,11 +132,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ variables: { id: 3 } })).subscribe((result) => { link.request(mockOperation({ variables: { id: 3 } })).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('forwards requests if different variables are set', (done) => { it('forwards requests if different variables are set', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -154,11 +149,10 @@ describe('StartupJSLink', () => { ...@@ -154,11 +149,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ variables: { id: 3 } })).subscribe((result) => { link.request(mockOperation({ variables: { id: 3 } })).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('forwards requests if array variables have a different order', (done) => { it('forwards requests if array variables have a different order', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -172,13 +166,12 @@ describe('StartupJSLink', () => { ...@@ -172,13 +166,12 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ variables: { id: [4, 3] } })).subscribe((result) => { link.request(mockOperation({ variables: { id: [4, 3] } })).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
}); });
describe('error handling', () => { describe('error handling', () => {
it('forwards the call if the fetchCall is failing with a HTTP Error', (done) => { it('forwards the call if the fetchCall is failing with a HTTP Error', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -192,11 +185,10 @@ describe('StartupJSLink', () => { ...@@ -192,11 +185,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('forwards the call if it errors (e.g. failing JSON)', (done) => { it('forwards the call if it errors (e.g. failing JSON)', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -210,11 +202,10 @@ describe('StartupJSLink', () => { ...@@ -210,11 +202,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('forwards the call if the response contains an error', (done) => { it('forwards the call if the response contains an error', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -228,11 +219,10 @@ describe('StartupJSLink', () => { ...@@ -228,11 +219,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it("forwards the call if the response doesn't contain a data object", (done) => { it("forwards the call if the response doesn't contain a data object", () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -246,12 +236,11 @@ describe('StartupJSLink', () => { ...@@ -246,12 +236,11 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(FORWARDED_RESPONSE); expect(result).toEqual(FORWARDED_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
}); });
it('resolves the request if the operation is matching', (done) => { it('resolves the request if the operation is matching', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -265,11 +254,10 @@ describe('StartupJSLink', () => { ...@@ -265,11 +254,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(STARTUP_JS_RESPONSE); expect(result).toEqual(STARTUP_JS_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('resolves the request exactly once', (done) => { it('resolves the request exactly once', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -285,12 +273,11 @@ describe('StartupJSLink', () => { ...@@ -285,12 +273,11 @@ describe('StartupJSLink', () => {
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
link.request(mockOperation()).subscribe((result2) => { link.request(mockOperation()).subscribe((result2) => {
expect(result2).toEqual(FORWARDED_RESPONSE); expect(result2).toEqual(FORWARDED_RESPONSE);
done();
}); });
}); });
}); });
it('resolves the request if the variables have a different order', (done) => { it('resolves the request if the variables have a different order', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -304,11 +291,10 @@ describe('StartupJSLink', () => { ...@@ -304,11 +291,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ variables: { name: 'foo', id: 3 } })).subscribe((result) => { link.request(mockOperation({ variables: { name: 'foo', id: 3 } })).subscribe((result) => {
expect(result).toEqual(STARTUP_JS_RESPONSE); expect(result).toEqual(STARTUP_JS_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('resolves the request if the variables have undefined values', (done) => { it('resolves the request if the variables have undefined values', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -324,11 +310,10 @@ describe('StartupJSLink', () => { ...@@ -324,11 +310,10 @@ describe('StartupJSLink', () => {
.subscribe((result) => { .subscribe((result) => {
expect(result).toEqual(STARTUP_JS_RESPONSE); expect(result).toEqual(STARTUP_JS_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('resolves the request if the variables are of an array format', (done) => { it('resolves the request if the variables are of an array format', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -342,11 +327,10 @@ describe('StartupJSLink', () => { ...@@ -342,11 +327,10 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ variables: { id: [3, 4] } })).subscribe((result) => { link.request(mockOperation({ variables: { id: [3, 4] } })).subscribe((result) => {
expect(result).toEqual(STARTUP_JS_RESPONSE); expect(result).toEqual(STARTUP_JS_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
it('resolves multiple requests correctly', (done) => { it('resolves multiple requests correctly', () => {
window.gl = { window.gl = {
startup_graphql_calls: [ startup_graphql_calls: [
{ {
...@@ -368,7 +352,6 @@ describe('StartupJSLink', () => { ...@@ -368,7 +352,6 @@ describe('StartupJSLink', () => {
link.request(mockOperation({ operationName: OPERATION_NAME })).subscribe((result2) => { link.request(mockOperation({ operationName: OPERATION_NAME })).subscribe((result2) => {
expect(result2).toEqual(STARTUP_JS_RESPONSE); expect(result2).toEqual(STARTUP_JS_RESPONSE);
expect(startupLink.startupCalls.size).toBe(0); expect(startupLink.startupCalls.size).toBe(0);
done();
}); });
}); });
}); });
......
...@@ -266,15 +266,18 @@ describe('common_utils', () => { ...@@ -266,15 +266,18 @@ describe('common_utils', () => {
}); });
describe('debounceByAnimationFrame', () => { describe('debounceByAnimationFrame', () => {
it('debounces a function to allow a maximum of one call per animation frame', (done) => { it('debounces a function to allow a maximum of one call per animation frame', () => {
const spy = jest.fn(); const spy = jest.fn();
const debouncedSpy = commonUtils.debounceByAnimationFrame(spy); const debouncedSpy = commonUtils.debounceByAnimationFrame(spy);
window.requestAnimationFrame(() => {
debouncedSpy(); return new Promise((resolve) => {
debouncedSpy();
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
expect(spy).toHaveBeenCalledTimes(1); debouncedSpy();
done(); debouncedSpy();
window.requestAnimationFrame(() => {
expect(spy).toHaveBeenCalledTimes(1);
resolve();
});
}); });
}); });
}); });
...@@ -372,28 +375,24 @@ describe('common_utils', () => { ...@@ -372,28 +375,24 @@ describe('common_utils', () => {
jest.spyOn(window, 'setTimeout'); jest.spyOn(window, 'setTimeout');
}); });
it('solves the promise from the callback', (done) => { it('solves the promise from the callback', () => {
const expectedResponseValue = 'Success!'; const expectedResponseValue = 'Success!';
commonUtils return commonUtils
.backOff((next, stop) => .backOff((next, stop) =>
new Promise((resolve) => { new Promise((resolve) => {
resolve(expectedResponseValue); resolve(expectedResponseValue);
}) }).then((resp) => {
.then((resp) => { stop(resp);
stop(resp); }),
})
.catch(done.fail),
) )
.then((respBackoff) => { .then((respBackoff) => {
expect(respBackoff).toBe(expectedResponseValue); expect(respBackoff).toBe(expectedResponseValue);
done(); });
})
.catch(done.fail);
}); });
it('catches the rejected promise from the callback ', (done) => { it('catches the rejected promise from the callback ', () => {
const errorMessage = 'Mistakes were made!'; const errorMessage = 'Mistakes were made!';
commonUtils return commonUtils
.backOff((next, stop) => { .backOff((next, stop) => {
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
reject(new Error(errorMessage)); reject(new Error(errorMessage));
...@@ -406,39 +405,34 @@ describe('common_utils', () => { ...@@ -406,39 +405,34 @@ describe('common_utils', () => {
.catch((errBackoffResp) => { .catch((errBackoffResp) => {
expect(errBackoffResp instanceof Error).toBe(true); expect(errBackoffResp instanceof Error).toBe(true);
expect(errBackoffResp.message).toBe(errorMessage); expect(errBackoffResp.message).toBe(errorMessage);
done();
}); });
}); });
it('solves the promise correctly after retrying a third time', (done) => { it('solves the promise correctly after retrying a third time', () => {
let numberOfCalls = 1; let numberOfCalls = 1;
const expectedResponseValue = 'Success!'; const expectedResponseValue = 'Success!';
commonUtils return commonUtils
.backOff((next, stop) => .backOff((next, stop) =>
Promise.resolve(expectedResponseValue) Promise.resolve(expectedResponseValue).then((resp) => {
.then((resp) => { if (numberOfCalls < 3) {
if (numberOfCalls < 3) { numberOfCalls += 1;
numberOfCalls += 1; next();
next(); jest.runOnlyPendingTimers();
jest.runOnlyPendingTimers(); } else {
} else { stop(resp);
stop(resp); }
} }),
})
.catch(done.fail),
) )
.then((respBackoff) => { .then((respBackoff) => {
const timeouts = window.setTimeout.mock.calls.map(([, timeout]) => timeout); const timeouts = window.setTimeout.mock.calls.map(([, timeout]) => timeout);
expect(timeouts).toEqual([2000, 4000]); expect(timeouts).toEqual([2000, 4000]);
expect(respBackoff).toBe(expectedResponseValue); expect(respBackoff).toBe(expectedResponseValue);
done(); });
})
.catch(done.fail);
}); });
it('rejects the backOff promise after timing out', (done) => { it('rejects the backOff promise after timing out', () => {
commonUtils return commonUtils
.backOff((next) => { .backOff((next) => {
next(); next();
jest.runOnlyPendingTimers(); jest.runOnlyPendingTimers();
...@@ -449,7 +443,6 @@ describe('common_utils', () => { ...@@ -449,7 +443,6 @@ describe('common_utils', () => {
expect(timeouts).toEqual([2000, 4000, 8000, 16000, 32000, 32000]); expect(timeouts).toEqual([2000, 4000, 8000, 16000, 32000, 32000]);
expect(errBackoffResp instanceof Error).toBe(true); expect(errBackoffResp instanceof Error).toBe(true);
expect(errBackoffResp.message).toBe('BACKOFF_TIMEOUT'); expect(errBackoffResp.message).toBe('BACKOFF_TIMEOUT');
done();
}); });
}); });
}); });
......
...@@ -50,58 +50,48 @@ describe('Poll', () => { ...@@ -50,58 +50,48 @@ describe('Poll', () => {
}; };
}); });
it('calls the success callback when no header for interval is provided', (done) => { it('calls the success callback when no header for interval is provided', () => {
mockServiceCall({ status: 200 }); mockServiceCall({ status: 200 });
setup(); setup();
waitForAllCallsToFinish(1, () => { return waitForAllCallsToFinish(1, () => {
expect(callbacks.success).toHaveBeenCalled(); expect(callbacks.success).toHaveBeenCalled();
expect(callbacks.error).not.toHaveBeenCalled(); expect(callbacks.error).not.toHaveBeenCalled();
done();
}); });
}); });
it('calls the error callback when the http request returns an error', (done) => { it('calls the error callback when the http request returns an error', () => {
mockServiceCall({ status: 500 }, true); mockServiceCall({ status: 500 }, true);
setup(); setup();
waitForAllCallsToFinish(1, () => { return waitForAllCallsToFinish(1, () => {
expect(callbacks.success).not.toHaveBeenCalled(); expect(callbacks.success).not.toHaveBeenCalled();
expect(callbacks.error).toHaveBeenCalled(); expect(callbacks.error).toHaveBeenCalled();
done();
}); });
}); });
it('skips the error callback when request is aborted', (done) => { it('skips the error callback when request is aborted', () => {
mockServiceCall({ status: 0 }, true); mockServiceCall({ status: 0 }, true);
setup(); setup();
waitForAllCallsToFinish(1, () => { return waitForAllCallsToFinish(1, () => {
expect(callbacks.success).not.toHaveBeenCalled(); expect(callbacks.success).not.toHaveBeenCalled();
expect(callbacks.error).not.toHaveBeenCalled(); expect(callbacks.error).not.toHaveBeenCalled();
expect(callbacks.notification).toHaveBeenCalled(); expect(callbacks.notification).toHaveBeenCalled();
done();
}); });
}); });
it('should call the success callback when the interval header is -1', (done) => { it('should call the success callback when the interval header is -1', () => {
mockServiceCall({ status: 200, headers: { 'poll-interval': -1 } }); mockServiceCall({ status: 200, headers: { 'poll-interval': -1 } });
setup() return setup().then(() => {
.then(() => { expect(callbacks.success).toHaveBeenCalled();
expect(callbacks.success).toHaveBeenCalled(); expect(callbacks.error).not.toHaveBeenCalled();
expect(callbacks.error).not.toHaveBeenCalled(); });
done();
})
.catch(done.fail);
}); });
describe('for 2xx status code', () => { describe('for 2xx status code', () => {
successCodes.forEach((httpCode) => { successCodes.forEach((httpCode) => {
it(`starts polling when http status is ${httpCode} and interval header is provided`, (done) => { it(`starts polling when http status is ${httpCode} and interval header is provided`, () => {
mockServiceCall({ status: httpCode, headers: { 'poll-interval': 1 } }); mockServiceCall({ status: httpCode, headers: { 'poll-interval': 1 } });
const Polling = new Poll({ const Polling = new Poll({
...@@ -114,22 +104,20 @@ describe('Poll', () => { ...@@ -114,22 +104,20 @@ describe('Poll', () => {
Polling.makeRequest(); Polling.makeRequest();
waitForAllCallsToFinish(2, () => { return waitForAllCallsToFinish(2, () => {
Polling.stop(); Polling.stop();
expect(service.fetch.mock.calls).toHaveLength(2); expect(service.fetch.mock.calls).toHaveLength(2);
expect(service.fetch).toHaveBeenCalledWith({ page: 1 }); expect(service.fetch).toHaveBeenCalledWith({ page: 1 });
expect(callbacks.success).toHaveBeenCalled(); expect(callbacks.success).toHaveBeenCalled();
expect(callbacks.error).not.toHaveBeenCalled(); expect(callbacks.error).not.toHaveBeenCalled();
done();
}); });
}); });
}); });
}); });
describe('with delayed initial request', () => { describe('with delayed initial request', () => {
it('delays the first request', async (done) => { it('delays the first request', async () => {
mockServiceCall({ status: 200, headers: { 'poll-interval': 1 } }); mockServiceCall({ status: 200, headers: { 'poll-interval': 1 } });
const Polling = new Poll({ const Polling = new Poll({
...@@ -144,21 +132,19 @@ describe('Poll', () => { ...@@ -144,21 +132,19 @@ describe('Poll', () => {
expect(Polling.timeoutID).toBeTruthy(); expect(Polling.timeoutID).toBeTruthy();
waitForAllCallsToFinish(2, () => { return waitForAllCallsToFinish(2, () => {
Polling.stop(); Polling.stop();
expect(service.fetch.mock.calls).toHaveLength(2); expect(service.fetch.mock.calls).toHaveLength(2);
expect(service.fetch).toHaveBeenCalledWith({ page: 1 }); expect(service.fetch).toHaveBeenCalledWith({ page: 1 });
expect(callbacks.success).toHaveBeenCalled(); expect(callbacks.success).toHaveBeenCalled();
expect(callbacks.error).not.toHaveBeenCalled(); expect(callbacks.error).not.toHaveBeenCalled();
done();
}); });
}); });
}); });
describe('stop', () => { describe('stop', () => {
it('stops polling when method is called', (done) => { it('stops polling when method is called', () => {
mockServiceCall({ status: 200, headers: { 'poll-interval': 1 } }); mockServiceCall({ status: 200, headers: { 'poll-interval': 1 } });
const Polling = new Poll({ const Polling = new Poll({
...@@ -175,18 +161,16 @@ describe('Poll', () => { ...@@ -175,18 +161,16 @@ describe('Poll', () => {
Polling.makeRequest(); Polling.makeRequest();
waitForAllCallsToFinish(1, () => { return waitForAllCallsToFinish(1, () => {
expect(service.fetch.mock.calls).toHaveLength(1); expect(service.fetch.mock.calls).toHaveLength(1);
expect(service.fetch).toHaveBeenCalledWith({ page: 1 }); expect(service.fetch).toHaveBeenCalledWith({ page: 1 });
expect(Polling.stop).toHaveBeenCalled(); expect(Polling.stop).toHaveBeenCalled();
done();
}); });
}); });
}); });
describe('enable', () => { describe('enable', () => {
it('should enable polling upon a response', (done) => { it('should enable polling upon a response', () => {
mockServiceCall({ status: 200 }); mockServiceCall({ status: 200 });
const Polling = new Poll({ const Polling = new Poll({
resource: service, resource: service,
...@@ -200,19 +184,18 @@ describe('Poll', () => { ...@@ -200,19 +184,18 @@ describe('Poll', () => {
response: { status: 200, headers: { 'poll-interval': 1 } }, response: { status: 200, headers: { 'poll-interval': 1 } },
}); });
waitForAllCallsToFinish(1, () => { return waitForAllCallsToFinish(1, () => {
Polling.stop(); Polling.stop();
expect(service.fetch.mock.calls).toHaveLength(1); expect(service.fetch.mock.calls).toHaveLength(1);
expect(service.fetch).toHaveBeenCalledWith({ page: 4 }); expect(service.fetch).toHaveBeenCalledWith({ page: 4 });
expect(Polling.options.data).toEqual({ page: 4 }); expect(Polling.options.data).toEqual({ page: 4 });
done();
}); });
}); });
}); });
describe('restart', () => { describe('restart', () => {
it('should restart polling when its called', (done) => { it('should restart polling when its called', () => {
mockServiceCall({ status: 200, headers: { 'poll-interval': 1 } }); mockServiceCall({ status: 200, headers: { 'poll-interval': 1 } });
const Polling = new Poll({ const Polling = new Poll({
...@@ -238,7 +221,7 @@ describe('Poll', () => { ...@@ -238,7 +221,7 @@ describe('Poll', () => {
Polling.makeRequest(); Polling.makeRequest();
waitForAllCallsToFinish(2, () => { return waitForAllCallsToFinish(2, () => {
Polling.stop(); Polling.stop();
expect(service.fetch.mock.calls).toHaveLength(2); expect(service.fetch.mock.calls).toHaveLength(2);
...@@ -247,7 +230,6 @@ describe('Poll', () => { ...@@ -247,7 +230,6 @@ describe('Poll', () => {
expect(Polling.enable).toHaveBeenCalled(); expect(Polling.enable).toHaveBeenCalled();
expect(Polling.restart).toHaveBeenCalled(); expect(Polling.restart).toHaveBeenCalled();
expect(Polling.options.data).toEqual({ page: 4 }); expect(Polling.options.data).toEqual({ page: 4 });
done();
}); });
}); });
}); });
......
...@@ -93,7 +93,7 @@ describe('UsersCache', () => { ...@@ -93,7 +93,7 @@ describe('UsersCache', () => {
.mockImplementation((query, options) => apiSpy(query, options)); .mockImplementation((query, options) => apiSpy(query, options));
}); });
it('stores and returns data from API call if cache is empty', (done) => { it('stores and returns data from API call if cache is empty', async () => {
apiSpy = (query, options) => { apiSpy = (query, options) => {
expect(query).toBe(''); expect(query).toBe('');
expect(options).toEqual({ expect(options).toEqual({
...@@ -105,16 +105,12 @@ describe('UsersCache', () => { ...@@ -105,16 +105,12 @@ describe('UsersCache', () => {
}); });
}; };
UsersCache.retrieve(dummyUsername) const user = await UsersCache.retrieve(dummyUsername);
.then((user) => { expect(user).toBe(dummyUser);
expect(user).toBe(dummyUser); expect(UsersCache.internalStorage[dummyUsername]).toBe(dummyUser);
expect(UsersCache.internalStorage[dummyUsername]).toBe(dummyUser);
})
.then(done)
.catch(done.fail);
}); });
it('returns undefined if Ajax call fails and cache is empty', (done) => { it('returns undefined if Ajax call fails and cache is empty', async () => {
const dummyError = new Error('server exploded'); const dummyError = new Error('server exploded');
apiSpy = (query, options) => { apiSpy = (query, options) => {
...@@ -126,26 +122,18 @@ describe('UsersCache', () => { ...@@ -126,26 +122,18 @@ describe('UsersCache', () => {
return Promise.reject(dummyError); return Promise.reject(dummyError);
}; };
UsersCache.retrieve(dummyUsername) await expect(UsersCache.retrieve(dummyUsername)).rejects.toEqual(dummyError);
.then((user) => done.fail(`Received unexpected user: ${JSON.stringify(user)}`))
.catch((error) => {
expect(error).toBe(dummyError);
})
.then(done)
.catch(done.fail);
}); });
it('makes no Ajax call if matching data exists', (done) => { it('makes no Ajax call if matching data exists', async () => {
UsersCache.internalStorage[dummyUsername] = dummyUser; UsersCache.internalStorage[dummyUsername] = dummyUser;
apiSpy = () => done.fail(new Error('expected no Ajax call!')); apiSpy = () => {
throw new Error('expected no Ajax call!');
};
UsersCache.retrieve(dummyUsername) const user = await UsersCache.retrieve(dummyUsername);
.then((user) => { expect(user).toBe(dummyUser);
expect(user).toBe(dummyUser);
})
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -156,7 +144,7 @@ describe('UsersCache', () => { ...@@ -156,7 +144,7 @@ describe('UsersCache', () => {
jest.spyOn(UserApi, 'getUser').mockImplementation((id) => apiSpy(id)); jest.spyOn(UserApi, 'getUser').mockImplementation((id) => apiSpy(id));
}); });
it('stores and returns data from API call if cache is empty', (done) => { it('stores and returns data from API call if cache is empty', async () => {
apiSpy = (id) => { apiSpy = (id) => {
expect(id).toBe(dummyUserId); expect(id).toBe(dummyUserId);
...@@ -165,16 +153,12 @@ describe('UsersCache', () => { ...@@ -165,16 +153,12 @@ describe('UsersCache', () => {
}); });
}; };
UsersCache.retrieveById(dummyUserId) const user = await UsersCache.retrieveById(dummyUserId);
.then((user) => { expect(user).toBe(dummyUser);
expect(user).toBe(dummyUser); expect(UsersCache.internalStorage[dummyUserId]).toBe(dummyUser);
expect(UsersCache.internalStorage[dummyUserId]).toBe(dummyUser);
})
.then(done)
.catch(done.fail);
}); });
it('returns undefined if Ajax call fails and cache is empty', (done) => { it('returns undefined if Ajax call fails and cache is empty', async () => {
const dummyError = new Error('server exploded'); const dummyError = new Error('server exploded');
apiSpy = (id) => { apiSpy = (id) => {
...@@ -183,26 +167,18 @@ describe('UsersCache', () => { ...@@ -183,26 +167,18 @@ describe('UsersCache', () => {
return Promise.reject(dummyError); return Promise.reject(dummyError);
}; };
UsersCache.retrieveById(dummyUserId) await expect(UsersCache.retrieveById(dummyUserId)).rejects.toEqual(dummyError);
.then((user) => done.fail(`Received unexpected user: ${JSON.stringify(user)}`))
.catch((error) => {
expect(error).toBe(dummyError);
})
.then(done)
.catch(done.fail);
}); });
it('makes no Ajax call if matching data exists', (done) => { it('makes no Ajax call if matching data exists', async () => {
UsersCache.internalStorage[dummyUserId] = dummyUser; UsersCache.internalStorage[dummyUserId] = dummyUser;
apiSpy = () => done.fail(new Error('expected no Ajax call!')); apiSpy = () => {
throw new Error('expected no Ajax call!');
};
UsersCache.retrieveById(dummyUserId) const user = await UsersCache.retrieveById(dummyUserId);
.then((user) => { expect(user).toBe(dummyUser);
expect(user).toBe(dummyUser);
})
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -213,7 +189,7 @@ describe('UsersCache', () => { ...@@ -213,7 +189,7 @@ describe('UsersCache', () => {
jest.spyOn(UserApi, 'getUserStatus').mockImplementation((id) => apiSpy(id)); jest.spyOn(UserApi, 'getUserStatus').mockImplementation((id) => apiSpy(id));
}); });
it('stores and returns data from API call if cache is empty', (done) => { it('stores and returns data from API call if cache is empty', async () => {
apiSpy = (id) => { apiSpy = (id) => {
expect(id).toBe(dummyUserId); expect(id).toBe(dummyUserId);
...@@ -222,16 +198,12 @@ describe('UsersCache', () => { ...@@ -222,16 +198,12 @@ describe('UsersCache', () => {
}); });
}; };
UsersCache.retrieveStatusById(dummyUserId) const userStatus = await UsersCache.retrieveStatusById(dummyUserId);
.then((userStatus) => { expect(userStatus).toBe(dummyUserStatus);
expect(userStatus).toBe(dummyUserStatus); expect(UsersCache.internalStorage[dummyUserId].status).toBe(dummyUserStatus);
expect(UsersCache.internalStorage[dummyUserId].status).toBe(dummyUserStatus);
})
.then(done)
.catch(done.fail);
}); });
it('returns undefined if Ajax call fails and cache is empty', (done) => { it('returns undefined if Ajax call fails and cache is empty', async () => {
const dummyError = new Error('server exploded'); const dummyError = new Error('server exploded');
apiSpy = (id) => { apiSpy = (id) => {
...@@ -240,28 +212,20 @@ describe('UsersCache', () => { ...@@ -240,28 +212,20 @@ describe('UsersCache', () => {
return Promise.reject(dummyError); return Promise.reject(dummyError);
}; };
UsersCache.retrieveStatusById(dummyUserId) await expect(UsersCache.retrieveStatusById(dummyUserId)).rejects.toEqual(dummyError);
.then((userStatus) => done.fail(`Received unexpected user: ${JSON.stringify(userStatus)}`))
.catch((error) => {
expect(error).toBe(dummyError);
})
.then(done)
.catch(done.fail);
}); });
it('makes no Ajax call if matching data exists', (done) => { it('makes no Ajax call if matching data exists', async () => {
UsersCache.internalStorage[dummyUserId] = { UsersCache.internalStorage[dummyUserId] = {
status: dummyUserStatus, status: dummyUserStatus,
}; };
apiSpy = () => done.fail(new Error('expected no Ajax call!')); apiSpy = () => {
throw new Error('expected no Ajax call!');
};
UsersCache.retrieveStatusById(dummyUserId) const userStatus = await UsersCache.retrieveStatusById(dummyUserId);
.then((userStatus) => { expect(userStatus).toBe(dummyUserStatus);
expect(userStatus).toBe(dummyUserStatus);
})
.then(done)
.catch(done.fail);
}); });
}); });
}); });
...@@ -34,9 +34,9 @@ describe('merge conflicts actions', () => { ...@@ -34,9 +34,9 @@ describe('merge conflicts actions', () => {
describe('fetchConflictsData', () => { describe('fetchConflictsData', () => {
const conflictsPath = 'conflicts/path/mock'; const conflictsPath = 'conflicts/path/mock';
it('on success dispatches setConflictsData', (done) => { it('on success dispatches setConflictsData', () => {
mock.onGet(conflictsPath).reply(200, {}); mock.onGet(conflictsPath).reply(200, {});
testAction( return testAction(
actions.fetchConflictsData, actions.fetchConflictsData,
conflictsPath, conflictsPath,
{}, {},
...@@ -45,13 +45,12 @@ describe('merge conflicts actions', () => { ...@@ -45,13 +45,12 @@ describe('merge conflicts actions', () => {
{ type: types.SET_LOADING_STATE, payload: false }, { type: types.SET_LOADING_STATE, payload: false },
], ],
[{ type: 'setConflictsData', payload: {} }], [{ type: 'setConflictsData', payload: {} }],
done,
); );
}); });
it('when data has type equal to error ', (done) => { it('when data has type equal to error ', () => {
mock.onGet(conflictsPath).reply(200, { type: 'error', message: 'error message' }); mock.onGet(conflictsPath).reply(200, { type: 'error', message: 'error message' });
testAction( return testAction(
actions.fetchConflictsData, actions.fetchConflictsData,
conflictsPath, conflictsPath,
{}, {},
...@@ -61,13 +60,12 @@ describe('merge conflicts actions', () => { ...@@ -61,13 +60,12 @@ describe('merge conflicts actions', () => {
{ type: types.SET_LOADING_STATE, payload: false }, { type: types.SET_LOADING_STATE, payload: false },
], ],
[], [],
done,
); );
}); });
it('when request fails ', (done) => { it('when request fails ', () => {
mock.onGet(conflictsPath).reply(400); mock.onGet(conflictsPath).reply(400);
testAction( return testAction(
actions.fetchConflictsData, actions.fetchConflictsData,
conflictsPath, conflictsPath,
{}, {},
...@@ -77,15 +75,14 @@ describe('merge conflicts actions', () => { ...@@ -77,15 +75,14 @@ describe('merge conflicts actions', () => {
{ type: types.SET_LOADING_STATE, payload: false }, { type: types.SET_LOADING_STATE, payload: false },
], ],
[], [],
done,
); );
}); });
}); });
describe('setConflictsData', () => { describe('setConflictsData', () => {
it('INTERACTIVE_RESOLVE_MODE updates the correct file ', (done) => { it('INTERACTIVE_RESOLVE_MODE updates the correct file ', () => {
decorateFiles.mockReturnValue([{ bar: 'baz' }]); decorateFiles.mockReturnValue([{ bar: 'baz' }]);
testAction( return testAction(
actions.setConflictsData, actions.setConflictsData,
{ files, foo: 'bar' }, { files, foo: 'bar' },
{}, {},
...@@ -96,7 +93,6 @@ describe('merge conflicts actions', () => { ...@@ -96,7 +93,6 @@ describe('merge conflicts actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -105,24 +101,21 @@ describe('merge conflicts actions', () => { ...@@ -105,24 +101,21 @@ describe('merge conflicts actions', () => {
useMockLocationHelper(); useMockLocationHelper();
const resolveConflictsPath = 'resolve/conflicts/path/mock'; const resolveConflictsPath = 'resolve/conflicts/path/mock';
it('on success reloads the page', (done) => { it('on success reloads the page', async () => {
mock.onPost(resolveConflictsPath).reply(200, { redirect_to: 'hrefPath' }); mock.onPost(resolveConflictsPath).reply(200, { redirect_to: 'hrefPath' });
testAction( await testAction(
actions.submitResolvedConflicts, actions.submitResolvedConflicts,
resolveConflictsPath, resolveConflictsPath,
{}, {},
[{ type: types.SET_SUBMIT_STATE, payload: true }], [{ type: types.SET_SUBMIT_STATE, payload: true }],
[], [],
() => {
expect(window.location.assign).toHaveBeenCalledWith('hrefPath');
done();
},
); );
expect(window.location.assign).toHaveBeenCalledWith('hrefPath');
}); });
it('on errors shows flash', (done) => { it('on errors shows flash', async () => {
mock.onPost(resolveConflictsPath).reply(400); mock.onPost(resolveConflictsPath).reply(400);
testAction( await testAction(
actions.submitResolvedConflicts, actions.submitResolvedConflicts,
resolveConflictsPath, resolveConflictsPath,
{}, {},
...@@ -131,13 +124,10 @@ describe('merge conflicts actions', () => { ...@@ -131,13 +124,10 @@ describe('merge conflicts actions', () => {
{ type: types.SET_SUBMIT_STATE, payload: false }, { type: types.SET_SUBMIT_STATE, payload: false },
], ],
[], [],
() => {
expect(createFlash).toHaveBeenCalledWith({
message: 'Failed to save merge conflicts resolutions. Please try again!',
});
done();
},
); );
expect(createFlash).toHaveBeenCalledWith({
message: 'Failed to save merge conflicts resolutions. Please try again!',
});
}); });
}); });
...@@ -193,9 +183,9 @@ describe('merge conflicts actions', () => { ...@@ -193,9 +183,9 @@ describe('merge conflicts actions', () => {
}); });
describe('setViewType', () => { describe('setViewType', () => {
it('commits the right mutation', (done) => { it('commits the right mutation', async () => {
const payload = 'viewType'; const payload = 'viewType';
testAction( await testAction(
actions.setViewType, actions.setViewType,
payload, payload,
{}, {},
...@@ -206,14 +196,11 @@ describe('merge conflicts actions', () => { ...@@ -206,14 +196,11 @@ describe('merge conflicts actions', () => {
}, },
], ],
[], [],
() => {
expect(Cookies.set).toHaveBeenCalledWith('diff_view', payload, {
expires: 365,
secure: false,
});
done();
},
); );
expect(Cookies.set).toHaveBeenCalledWith('diff_view', payload, {
expires: 365,
secure: false,
});
}); });
}); });
...@@ -252,8 +239,8 @@ describe('merge conflicts actions', () => { ...@@ -252,8 +239,8 @@ describe('merge conflicts actions', () => {
}); });
describe('setFileResolveMode', () => { describe('setFileResolveMode', () => {
it('INTERACTIVE_RESOLVE_MODE updates the correct file ', (done) => { it('INTERACTIVE_RESOLVE_MODE updates the correct file ', () => {
testAction( return testAction(
actions.setFileResolveMode, actions.setFileResolveMode,
{ file: files[0], mode: INTERACTIVE_RESOLVE_MODE }, { file: files[0], mode: INTERACTIVE_RESOLVE_MODE },
{ conflictsData: { files }, getFileIndex: () => 0 }, { conflictsData: { files }, getFileIndex: () => 0 },
...@@ -267,11 +254,10 @@ describe('merge conflicts actions', () => { ...@@ -267,11 +254,10 @@ describe('merge conflicts actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('EDIT_RESOLVE_MODE updates the correct file ', (done) => { it('EDIT_RESOLVE_MODE updates the correct file ', async () => {
restoreFileLinesState.mockReturnValue([]); restoreFileLinesState.mockReturnValue([]);
const file = { const file = {
...files[0], ...files[0],
...@@ -280,7 +266,7 @@ describe('merge conflicts actions', () => { ...@@ -280,7 +266,7 @@ describe('merge conflicts actions', () => {
resolutionData: {}, resolutionData: {},
resolveMode: EDIT_RESOLVE_MODE, resolveMode: EDIT_RESOLVE_MODE,
}; };
testAction( await testAction(
actions.setFileResolveMode, actions.setFileResolveMode,
{ file: files[0], mode: EDIT_RESOLVE_MODE }, { file: files[0], mode: EDIT_RESOLVE_MODE },
{ conflictsData: { files }, getFileIndex: () => 0 }, { conflictsData: { files }, getFileIndex: () => 0 },
...@@ -294,17 +280,14 @@ describe('merge conflicts actions', () => { ...@@ -294,17 +280,14 @@ describe('merge conflicts actions', () => {
}, },
], ],
[], [],
() => {
expect(restoreFileLinesState).toHaveBeenCalledWith(file);
done();
},
); );
expect(restoreFileLinesState).toHaveBeenCalledWith(file);
}); });
}); });
describe('setPromptConfirmationState', () => { describe('setPromptConfirmationState', () => {
it('updates the correct file ', (done) => { it('updates the correct file ', () => {
testAction( return testAction(
actions.setPromptConfirmationState, actions.setPromptConfirmationState,
{ file: files[0], promptDiscardConfirmation: true }, { file: files[0], promptDiscardConfirmation: true },
{ conflictsData: { files }, getFileIndex: () => 0 }, { conflictsData: { files }, getFileIndex: () => 0 },
...@@ -318,7 +301,6 @@ describe('merge conflicts actions', () => { ...@@ -318,7 +301,6 @@ describe('merge conflicts actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -333,11 +315,11 @@ describe('merge conflicts actions', () => { ...@@ -333,11 +315,11 @@ describe('merge conflicts actions', () => {
], ],
}; };
it('updates the correct file ', (done) => { it('updates the correct file ', async () => {
const marLikeMockReturn = { foo: 'bar' }; const marLikeMockReturn = { foo: 'bar' };
markLine.mockReturnValue(marLikeMockReturn); markLine.mockReturnValue(marLikeMockReturn);
testAction( await testAction(
actions.handleSelected, actions.handleSelected,
{ file, line: { id: 1, section: 'baz' } }, { file, line: { id: 1, section: 'baz' } },
{ conflictsData: { files }, getFileIndex: () => 0 }, { conflictsData: { files }, getFileIndex: () => 0 },
...@@ -359,11 +341,8 @@ describe('merge conflicts actions', () => { ...@@ -359,11 +341,8 @@ describe('merge conflicts actions', () => {
}, },
], ],
[], [],
() => {
expect(markLine).toHaveBeenCalledTimes(3);
done();
},
); );
expect(markLine).toHaveBeenCalledTimes(3);
}); });
}); });
}); });
...@@ -32,7 +32,7 @@ describe('delete_milestone_modal.vue', () => { ...@@ -32,7 +32,7 @@ describe('delete_milestone_modal.vue', () => {
jest.spyOn(eventHub, '$emit').mockImplementation(() => {}); jest.spyOn(eventHub, '$emit').mockImplementation(() => {});
}); });
it('deletes milestone and redirects to overview page', (done) => { it('deletes milestone and redirects to overview page', async () => {
const responseURL = `${TEST_HOST}/delete_milestone_modal.vue/milestoneOverview`; const responseURL = `${TEST_HOST}/delete_milestone_modal.vue/milestoneOverview`;
jest.spyOn(axios, 'delete').mockImplementation((url) => { jest.spyOn(axios, 'delete').mockImplementation((url) => {
expect(url).toBe(props.milestoneUrl); expect(url).toBe(props.milestoneUrl);
...@@ -48,19 +48,15 @@ describe('delete_milestone_modal.vue', () => { ...@@ -48,19 +48,15 @@ describe('delete_milestone_modal.vue', () => {
}); });
}); });
vm.onSubmit() await vm.onSubmit();
.then(() => { expect(redirectTo).toHaveBeenCalledWith(responseURL);
expect(redirectTo).toHaveBeenCalledWith(responseURL); expect(eventHub.$emit).toHaveBeenCalledWith('deleteMilestoneModal.requestFinished', {
expect(eventHub.$emit).toHaveBeenCalledWith('deleteMilestoneModal.requestFinished', { milestoneUrl: props.milestoneUrl,
milestoneUrl: props.milestoneUrl, successful: true,
successful: true, });
});
})
.then(done)
.catch(done.fail);
}); });
it('displays error if deleting milestone failed', (done) => { it('displays error if deleting milestone failed', async () => {
const dummyError = new Error('deleting milestone failed'); const dummyError = new Error('deleting milestone failed');
dummyError.response = { status: 418 }; dummyError.response = { status: 418 };
jest.spyOn(axios, 'delete').mockImplementation((url) => { jest.spyOn(axios, 'delete').mockImplementation((url) => {
...@@ -73,17 +69,12 @@ describe('delete_milestone_modal.vue', () => { ...@@ -73,17 +69,12 @@ describe('delete_milestone_modal.vue', () => {
return Promise.reject(dummyError); return Promise.reject(dummyError);
}); });
vm.onSubmit() await expect(vm.onSubmit()).rejects.toEqual(dummyError);
.catch((error) => { expect(redirectTo).not.toHaveBeenCalled();
expect(error).toBe(dummyError); expect(eventHub.$emit).toHaveBeenCalledWith('deleteMilestoneModal.requestFinished', {
expect(redirectTo).not.toHaveBeenCalled(); milestoneUrl: props.milestoneUrl,
expect(eventHub.$emit).toHaveBeenCalledWith('deleteMilestoneModal.requestFinished', { successful: false,
milestoneUrl: props.milestoneUrl, });
successful: false,
});
})
.then(done)
.catch(done.fail);
}); });
}); });
......
...@@ -109,7 +109,7 @@ describe('Actions menu', () => { ...@@ -109,7 +109,7 @@ describe('Actions menu', () => {
describe('adding new metric from modal', () => { describe('adding new metric from modal', () => {
let origPage; let origPage;
beforeEach((done) => { beforeEach(() => {
jest.spyOn(Tracking, 'event').mockReturnValue(); jest.spyOn(Tracking, 'event').mockReturnValue();
createShallowWrapper(); createShallowWrapper();
...@@ -118,7 +118,7 @@ describe('Actions menu', () => { ...@@ -118,7 +118,7 @@ describe('Actions menu', () => {
origPage = document.body.dataset.page; origPage = document.body.dataset.page;
document.body.dataset.page = 'projects:environments:metrics'; document.body.dataset.page = 'projects:environments:metrics';
nextTick(done); return nextTick();
}); });
afterEach(() => { afterEach(() => {
......
...@@ -263,7 +263,7 @@ describe('NoteHeader component', () => { ...@@ -263,7 +263,7 @@ describe('NoteHeader component', () => {
}); });
describe('when author username link is hovered', () => { describe('when author username link is hovered', () => {
it('toggles hover specific CSS classes on author name link', (done) => { it('toggles hover specific CSS classes on author name link', async () => {
createComponent({ author }); createComponent({ author });
const authorUsernameLink = wrapper.find({ ref: 'authorUsernameLink' }); const authorUsernameLink = wrapper.find({ ref: 'authorUsernameLink' });
...@@ -271,19 +271,15 @@ describe('NoteHeader component', () => { ...@@ -271,19 +271,15 @@ describe('NoteHeader component', () => {
authorUsernameLink.trigger('mouseenter'); authorUsernameLink.trigger('mouseenter');
nextTick(() => { await nextTick();
expect(authorNameLink.classes()).toContain('hover'); expect(authorNameLink.classes()).toContain('hover');
expect(authorNameLink.classes()).toContain('text-underline'); expect(authorNameLink.classes()).toContain('text-underline');
authorUsernameLink.trigger('mouseleave'); authorUsernameLink.trigger('mouseleave');
nextTick(() => { await nextTick();
expect(authorNameLink.classes()).not.toContain('hover'); expect(authorNameLink.classes()).not.toContain('hover');
expect(authorNameLink.classes()).not.toContain('text-underline'); expect(authorNameLink.classes()).not.toContain('text-underline');
done();
});
});
}); });
}); });
......
...@@ -561,7 +561,7 @@ describe.skip('Old Notes (~/deprecated_notes.js)', () => { ...@@ -561,7 +561,7 @@ describe.skip('Old Notes (~/deprecated_notes.js)', () => {
}); });
describe('postComment', () => { describe('postComment', () => {
it('disables the submit button', (done) => { it('disables the submit button', async () => {
const $submitButton = $form.find('.js-comment-submit-button'); const $submitButton = $form.find('.js-comment-submit-button');
expect($submitButton).not.toBeDisabled(); expect($submitButton).not.toBeDisabled();
...@@ -574,13 +574,8 @@ describe.skip('Old Notes (~/deprecated_notes.js)', () => { ...@@ -574,13 +574,8 @@ describe.skip('Old Notes (~/deprecated_notes.js)', () => {
return [200, note]; return [200, note];
}); });
notes await notes.postComment(dummyEvent);
.postComment(dummyEvent) expect($submitButton).not.toBeDisabled();
.then(() => {
expect($submitButton).not.toBeDisabled();
})
.then(done)
.catch(done.fail);
}); });
}); });
......
This diff is collapsed.
...@@ -20,10 +20,10 @@ jest.mock('~/api.js'); ...@@ -20,10 +20,10 @@ jest.mock('~/api.js');
describe('Actions Package details store', () => { describe('Actions Package details store', () => {
describe('fetchPackageVersions', () => { describe('fetchPackageVersions', () => {
it('should fetch the package versions', (done) => { it('should fetch the package versions', async () => {
Api.projectPackage = jest.fn().mockResolvedValue({ data: packageEntity }); Api.projectPackage = jest.fn().mockResolvedValue({ data: packageEntity });
testAction( await testAction(
fetchPackageVersions, fetchPackageVersions,
undefined, undefined,
{ packageEntity }, { packageEntity },
...@@ -33,20 +33,14 @@ describe('Actions Package details store', () => { ...@@ -33,20 +33,14 @@ describe('Actions Package details store', () => {
{ type: types.SET_LOADING, payload: false }, { type: types.SET_LOADING, payload: false },
], ],
[], [],
() => {
expect(Api.projectPackage).toHaveBeenCalledWith(
packageEntity.project_id,
packageEntity.id,
);
done();
},
); );
expect(Api.projectPackage).toHaveBeenCalledWith(packageEntity.project_id, packageEntity.id);
}); });
it("does not set the versions if they don't exist", (done) => { it("does not set the versions if they don't exist", async () => {
Api.projectPackage = jest.fn().mockResolvedValue({ data: { packageEntity, versions: null } }); Api.projectPackage = jest.fn().mockResolvedValue({ data: { packageEntity, versions: null } });
testAction( await testAction(
fetchPackageVersions, fetchPackageVersions,
undefined, undefined,
{ packageEntity }, { packageEntity },
...@@ -55,20 +49,14 @@ describe('Actions Package details store', () => { ...@@ -55,20 +49,14 @@ describe('Actions Package details store', () => {
{ type: types.SET_LOADING, payload: false }, { type: types.SET_LOADING, payload: false },
], ],
[], [],
() => {
expect(Api.projectPackage).toHaveBeenCalledWith(
packageEntity.project_id,
packageEntity.id,
);
done();
},
); );
expect(Api.projectPackage).toHaveBeenCalledWith(packageEntity.project_id, packageEntity.id);
}); });
it('should create flash on API error', (done) => { it('should create flash on API error', async () => {
Api.projectPackage = jest.fn().mockRejectedValue(); Api.projectPackage = jest.fn().mockRejectedValue();
testAction( await testAction(
fetchPackageVersions, fetchPackageVersions,
undefined, undefined,
{ packageEntity }, { packageEntity },
...@@ -77,41 +65,31 @@ describe('Actions Package details store', () => { ...@@ -77,41 +65,31 @@ describe('Actions Package details store', () => {
{ type: types.SET_LOADING, payload: false }, { type: types.SET_LOADING, payload: false },
], ],
[], [],
() => {
expect(Api.projectPackage).toHaveBeenCalledWith(
packageEntity.project_id,
packageEntity.id,
);
expect(createFlash).toHaveBeenCalledWith({
message: FETCH_PACKAGE_VERSIONS_ERROR,
type: 'warning',
});
done();
},
); );
expect(Api.projectPackage).toHaveBeenCalledWith(packageEntity.project_id, packageEntity.id);
expect(createFlash).toHaveBeenCalledWith({
message: FETCH_PACKAGE_VERSIONS_ERROR,
type: 'warning',
});
}); });
}); });
describe('deletePackage', () => { describe('deletePackage', () => {
it('should call Api.deleteProjectPackage', (done) => { it('should call Api.deleteProjectPackage', async () => {
Api.deleteProjectPackage = jest.fn().mockResolvedValue(); Api.deleteProjectPackage = jest.fn().mockResolvedValue();
testAction(deletePackage, undefined, { packageEntity }, [], [], () => { await testAction(deletePackage, undefined, { packageEntity }, [], []);
expect(Api.deleteProjectPackage).toHaveBeenCalledWith( expect(Api.deleteProjectPackage).toHaveBeenCalledWith(
packageEntity.project_id, packageEntity.project_id,
packageEntity.id, packageEntity.id,
); );
done();
});
}); });
it('should create flash on API error', (done) => { it('should create flash on API error', async () => {
Api.deleteProjectPackage = jest.fn().mockRejectedValue(); Api.deleteProjectPackage = jest.fn().mockRejectedValue();
testAction(deletePackage, undefined, { packageEntity }, [], [], () => { await testAction(deletePackage, undefined, { packageEntity }, [], []);
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: DELETE_PACKAGE_ERROR_MESSAGE, message: DELETE_PACKAGE_ERROR_MESSAGE,
type: 'warning', type: 'warning',
});
done();
}); });
}); });
}); });
...@@ -119,37 +97,33 @@ describe('Actions Package details store', () => { ...@@ -119,37 +97,33 @@ describe('Actions Package details store', () => {
describe('deletePackageFile', () => { describe('deletePackageFile', () => {
const fileId = 'a_file_id'; const fileId = 'a_file_id';
it('should call Api.deleteProjectPackageFile and commit the right data', (done) => { it('should call Api.deleteProjectPackageFile and commit the right data', async () => {
const packageFiles = [{ id: 'foo' }, { id: fileId }]; const packageFiles = [{ id: 'foo' }, { id: fileId }];
Api.deleteProjectPackageFile = jest.fn().mockResolvedValue(); Api.deleteProjectPackageFile = jest.fn().mockResolvedValue();
testAction( await testAction(
deletePackageFile, deletePackageFile,
fileId, fileId,
{ packageEntity, packageFiles }, { packageEntity, packageFiles },
[{ type: types.UPDATE_PACKAGE_FILES, payload: [{ id: 'foo' }] }], [{ type: types.UPDATE_PACKAGE_FILES, payload: [{ id: 'foo' }] }],
[], [],
() => {
expect(Api.deleteProjectPackageFile).toHaveBeenCalledWith(
packageEntity.project_id,
packageEntity.id,
fileId,
);
expect(createFlash).toHaveBeenCalledWith({
message: DELETE_PACKAGE_FILE_SUCCESS_MESSAGE,
type: 'success',
});
done();
},
); );
expect(Api.deleteProjectPackageFile).toHaveBeenCalledWith(
packageEntity.project_id,
packageEntity.id,
fileId,
);
expect(createFlash).toHaveBeenCalledWith({
message: DELETE_PACKAGE_FILE_SUCCESS_MESSAGE,
type: 'success',
});
}); });
it('should create flash on API error', (done) => {
it('should create flash on API error', async () => {
Api.deleteProjectPackageFile = jest.fn().mockRejectedValue(); Api.deleteProjectPackageFile = jest.fn().mockRejectedValue();
testAction(deletePackageFile, fileId, { packageEntity }, [], [], () => { await testAction(deletePackageFile, fileId, { packageEntity }, [], []);
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: DELETE_PACKAGE_FILE_ERROR_MESSAGE, message: DELETE_PACKAGE_FILE_ERROR_MESSAGE,
type: 'warning', type: 'warning',
});
done();
}); });
}); });
}); });
......
...@@ -32,8 +32,8 @@ describe('Actions Package list store', () => { ...@@ -32,8 +32,8 @@ describe('Actions Package list store', () => {
}; };
const filter = []; const filter = [];
it('should fetch the project packages list when isGroupPage is false', (done) => { it('should fetch the project packages list when isGroupPage is false', async () => {
testAction( await testAction(
actions.requestPackagesList, actions.requestPackagesList,
undefined, undefined,
{ config: { isGroupPage: false, resourceId: 1 }, sorting, filter }, { config: { isGroupPage: false, resourceId: 1 }, sorting, filter },
...@@ -43,17 +43,14 @@ describe('Actions Package list store', () => { ...@@ -43,17 +43,14 @@ describe('Actions Package list store', () => {
{ type: 'receivePackagesListSuccess', payload: { data: 'foo', headers } }, { type: 'receivePackagesListSuccess', payload: { data: 'foo', headers } },
{ type: 'setLoading', payload: false }, { type: 'setLoading', payload: false },
], ],
() => {
expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy },
});
done();
},
); );
expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy },
});
}); });
it('should fetch the group packages list when isGroupPage is true', (done) => { it('should fetch the group packages list when isGroupPage is true', async () => {
testAction( await testAction(
actions.requestPackagesList, actions.requestPackagesList,
undefined, undefined,
{ config: { isGroupPage: true, resourceId: 2 }, sorting, filter }, { config: { isGroupPage: true, resourceId: 2 }, sorting, filter },
...@@ -63,19 +60,16 @@ describe('Actions Package list store', () => { ...@@ -63,19 +60,16 @@ describe('Actions Package list store', () => {
{ type: 'receivePackagesListSuccess', payload: { data: 'baz', headers } }, { type: 'receivePackagesListSuccess', payload: { data: 'baz', headers } },
{ type: 'setLoading', payload: false }, { type: 'setLoading', payload: false },
], ],
() => {
expect(Api.groupPackages).toHaveBeenCalledWith(2, {
params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy },
});
done();
},
); );
expect(Api.groupPackages).toHaveBeenCalledWith(2, {
params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy },
});
}); });
it('should fetch packages of a certain type when a filter with a type is present', (done) => { it('should fetch packages of a certain type when a filter with a type is present', async () => {
const packageType = 'maven'; const packageType = 'maven';
testAction( await testAction(
actions.requestPackagesList, actions.requestPackagesList,
undefined, undefined,
{ {
...@@ -89,24 +83,21 @@ describe('Actions Package list store', () => { ...@@ -89,24 +83,21 @@ describe('Actions Package list store', () => {
{ type: 'receivePackagesListSuccess', payload: { data: 'foo', headers } }, { type: 'receivePackagesListSuccess', payload: { data: 'foo', headers } },
{ type: 'setLoading', payload: false }, { type: 'setLoading', payload: false },
], ],
() => {
expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: {
page: 1,
per_page: 20,
sort: sorting.sort,
order_by: sorting.orderBy,
package_type: packageType,
},
});
done();
},
); );
expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: {
page: 1,
per_page: 20,
sort: sorting.sort,
order_by: sorting.orderBy,
package_type: packageType,
},
});
}); });
it('should create flash on API error', (done) => { it('should create flash on API error', async () => {
Api.projectPackages = jest.fn().mockRejectedValue(); Api.projectPackages = jest.fn().mockRejectedValue();
testAction( await testAction(
actions.requestPackagesList, actions.requestPackagesList,
undefined, undefined,
{ config: { isGroupPage: false, resourceId: 2 }, sorting, filter }, { config: { isGroupPage: false, resourceId: 2 }, sorting, filter },
...@@ -115,15 +106,12 @@ describe('Actions Package list store', () => { ...@@ -115,15 +106,12 @@ describe('Actions Package list store', () => {
{ type: 'setLoading', payload: true }, { type: 'setLoading', payload: true },
{ type: 'setLoading', payload: false }, { type: 'setLoading', payload: false },
], ],
() => {
expect(createFlash).toHaveBeenCalled();
done();
},
); );
expect(createFlash).toHaveBeenCalled();
}); });
it('should force the terraform_module type when forceTerraform is true', (done) => { it('should force the terraform_module type when forceTerraform is true', async () => {
testAction( await testAction(
actions.requestPackagesList, actions.requestPackagesList,
undefined, undefined,
{ config: { isGroupPage: false, resourceId: 1, forceTerraform: true }, sorting, filter }, { config: { isGroupPage: false, resourceId: 1, forceTerraform: true }, sorting, filter },
...@@ -133,27 +121,24 @@ describe('Actions Package list store', () => { ...@@ -133,27 +121,24 @@ describe('Actions Package list store', () => {
{ type: 'receivePackagesListSuccess', payload: { data: 'foo', headers } }, { type: 'receivePackagesListSuccess', payload: { data: 'foo', headers } },
{ type: 'setLoading', payload: false }, { type: 'setLoading', payload: false },
], ],
() => {
expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: {
page: 1,
per_page: 20,
sort: sorting.sort,
order_by: sorting.orderBy,
package_type: 'terraform_module',
},
});
done();
},
); );
expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: {
page: 1,
per_page: 20,
sort: sorting.sort,
order_by: sorting.orderBy,
package_type: 'terraform_module',
},
});
}); });
}); });
describe('receivePackagesListSuccess', () => { describe('receivePackagesListSuccess', () => {
it('should set received packages', (done) => { it('should set received packages', () => {
const data = 'foo'; const data = 'foo';
testAction( return testAction(
actions.receivePackagesListSuccess, actions.receivePackagesListSuccess,
{ data, headers }, { data, headers },
null, null,
...@@ -162,33 +147,30 @@ describe('Actions Package list store', () => { ...@@ -162,33 +147,30 @@ describe('Actions Package list store', () => {
{ type: types.SET_PAGINATION, payload: headers }, { type: types.SET_PAGINATION, payload: headers },
], ],
[], [],
done,
); );
}); });
}); });
describe('setInitialState', () => { describe('setInitialState', () => {
it('should commit setInitialState', (done) => { it('should commit setInitialState', () => {
testAction( return testAction(
actions.setInitialState, actions.setInitialState,
'1', '1',
null, null,
[{ type: types.SET_INITIAL_STATE, payload: '1' }], [{ type: types.SET_INITIAL_STATE, payload: '1' }],
[], [],
done,
); );
}); });
}); });
describe('setLoading', () => { describe('setLoading', () => {
it('should commit set main loading', (done) => { it('should commit set main loading', () => {
testAction( return testAction(
actions.setLoading, actions.setLoading,
true, true,
null, null,
[{ type: types.SET_MAIN_LOADING, payload: true }], [{ type: types.SET_MAIN_LOADING, payload: true }],
[], [],
done,
); );
}); });
}); });
...@@ -199,11 +181,11 @@ describe('Actions Package list store', () => { ...@@ -199,11 +181,11 @@ describe('Actions Package list store', () => {
delete_api_path: 'foo', delete_api_path: 'foo',
}, },
}; };
it('should perform a delete operation on _links.delete_api_path', (done) => { it('should perform a delete operation on _links.delete_api_path', () => {
mock.onDelete(payload._links.delete_api_path).replyOnce(200); mock.onDelete(payload._links.delete_api_path).replyOnce(200);
Api.projectPackages = jest.fn().mockResolvedValue({ data: 'foo' }); Api.projectPackages = jest.fn().mockResolvedValue({ data: 'foo' });
testAction( return testAction(
actions.requestDeletePackage, actions.requestDeletePackage,
payload, payload,
{ pagination: { page: 1 } }, { pagination: { page: 1 } },
...@@ -212,13 +194,12 @@ describe('Actions Package list store', () => { ...@@ -212,13 +194,12 @@ describe('Actions Package list store', () => {
{ type: 'setLoading', payload: true }, { type: 'setLoading', payload: true },
{ type: 'requestPackagesList', payload: { page: 1 } }, { type: 'requestPackagesList', payload: { page: 1 } },
], ],
done,
); );
}); });
it('should stop the loading and call create flash on api error', (done) => { it('should stop the loading and call create flash on api error', async () => {
mock.onDelete(payload._links.delete_api_path).replyOnce(400); mock.onDelete(payload._links.delete_api_path).replyOnce(400);
testAction( await testAction(
actions.requestDeletePackage, actions.requestDeletePackage,
payload, payload,
null, null,
...@@ -227,50 +208,44 @@ describe('Actions Package list store', () => { ...@@ -227,50 +208,44 @@ describe('Actions Package list store', () => {
{ type: 'setLoading', payload: true }, { type: 'setLoading', payload: true },
{ type: 'setLoading', payload: false }, { type: 'setLoading', payload: false },
], ],
() => {
expect(createFlash).toHaveBeenCalled();
done();
},
); );
expect(createFlash).toHaveBeenCalled();
}); });
it.each` it.each`
property | actionPayload property | actionPayload
${'_links'} | ${{}} ${'_links'} | ${{}}
${'delete_api_path'} | ${{ _links: {} }} ${'delete_api_path'} | ${{ _links: {} }}
`('should reject and createFlash when $property is missing', ({ actionPayload }, done) => { `('should reject and createFlash when $property is missing', ({ actionPayload }) => {
testAction(actions.requestDeletePackage, actionPayload, null, [], []).catch((e) => { return testAction(actions.requestDeletePackage, actionPayload, null, [], []).catch((e) => {
expect(e).toEqual(new Error(MISSING_DELETE_PATH_ERROR)); expect(e).toEqual(new Error(MISSING_DELETE_PATH_ERROR));
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: DELETE_PACKAGE_ERROR_MESSAGE, message: DELETE_PACKAGE_ERROR_MESSAGE,
}); });
done();
}); });
}); });
}); });
describe('setSorting', () => { describe('setSorting', () => {
it('should commit SET_SORTING', (done) => { it('should commit SET_SORTING', () => {
testAction( return testAction(
actions.setSorting, actions.setSorting,
'foo', 'foo',
null, null,
[{ type: types.SET_SORTING, payload: 'foo' }], [{ type: types.SET_SORTING, payload: 'foo' }],
[], [],
done,
); );
}); });
}); });
describe('setFilter', () => { describe('setFilter', () => {
it('should commit SET_FILTER', (done) => { it('should commit SET_FILTER', () => {
testAction( return testAction(
actions.setFilter, actions.setFilter,
'foo', 'foo',
null, null,
[{ type: types.SET_FILTER, payload: 'foo' }], [{ type: types.SET_FILTER, payload: 'foo' }],
[], [],
done,
); );
}); });
}); });
......
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