Commit 5e9fc348 authored by Vitaly Slobodin's avatar Vitaly Slobodin Committed by David O'Regan

Remove jest test callbacks from specs

Jest 27 does not support the test callback anymore so
the following code is no longer valid:

```
it('test', (done) => { /* code */ })
```
parent 45490c79
...@@ -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()
.then(() => {
expect(component.switchToFallbackUI).toHaveBeenCalled(); 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)
.catch((error) => {
expect(error).toBe(dummyError);
expect(dummyConfig.onLoadingFinished.mock.calls.length).toBe(0); 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)
.then(() => {
expect(createFlash.mock.calls.length).toBe(0); 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)
.then(() => {
expect(tokenValueElement.innerText).toBe(tokenValue); 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)
.then(() => {
expect(tokenValueContainer.dataset.originalValue).toBe(tokenValue); expect(tokenValueContainer.dataset.originalValue).toBe(tokenValue);
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name); expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
const avatar = tokenValueElement.querySelector('img.avatar'); const avatar = tokenValueElement.querySelector('img.avatar');
expect(avatar.getAttribute('src')).toBe(dummyUser.avatar_url); expect(avatar.getAttribute('src')).toBe(dummyUser.avatar_url);
expect(avatar.getAttribute('alt')).toBe(''); 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)
.then(() => {
expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name); expect(tokenValueElement.innerText.trim()).toBe(dummyUser.name);
tokenValueElement.querySelector('.avatar').remove(); 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)
.then(() => {
expectValueContainerStyle(tokenValueContainer, matchingLabel); 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)
.then(() => {
expectValueContainerStyle(tokenValueContainer, matchingLabel); 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)
.then(() => {
expect(tokenValueContainer.getAttribute('style')).toBe(null); 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();
});
it('should register click eventlistener to swipe view mode', (done) => { expect(changeViewSpy).toHaveBeenCalledWith(viewTypes.TWO_UP, expect.any(Object));
jest.spyOn(ReplacedImageDiff.prototype, 'changeView').mockImplementation((viewMode) => {
expect(viewMode).toEqual(viewTypes.SWIPE);
done();
}); });
it('should register click eventlistener to swipe view mode', () => {
const changeViewSpy = jest
.spyOn(ReplacedImageDiff.prototype, 'changeView')
.mockImplementation(() => {});
replacedImageDiff.bindEvents(); replacedImageDiff.bindEvents();
replacedImageDiff.viewModesEls[viewTypes.SWIPE].click(); replacedImageDiff.viewModesEls[viewTypes.SWIPE].click();
});
it('should register click eventlistener to onion skin view mode', (done) => { expect(changeViewSpy).toHaveBeenCalledWith(viewTypes.SWIPE, expect.any(Object));
jest.spyOn(ReplacedImageDiff.prototype, 'changeView').mockImplementation((viewMode) => {
expect(viewMode).toEqual(viewTypes.SWIPE);
done();
}); });
it('should register click eventlistener to onion skin view mode', () => {
const changeViewSpy = jest
.spyOn(ReplacedImageDiff.prototype, 'changeView')
.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')
.then(() => {
expect(axios.get).toHaveBeenCalledWith( expect(axios.get).toHaveBeenCalledWith(
endpoint, endpoint,
expect.objectContaining({ cancelToken: expect.anything() }), 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).toHaveBeenCalledTimes(1);
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: expect.stringMatching('Something went wrong'), message: expect.stringMatching('Something went wrong'),
}); });
done();
},
);
}); });
}); });
}); });
......
...@@ -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);
}); });
}); });
}); });
......
...@@ -39,62 +39,60 @@ describe('Job State actions', () => { ...@@ -39,62 +39,60 @@ describe('Job State actions', () => {
}); });
describe('setJobEndpoint', () => { describe('setJobEndpoint', () => {
it('should commit SET_JOB_ENDPOINT mutation', (done) => { it('should commit SET_JOB_ENDPOINT mutation', () => {
testAction( return testAction(
setJobEndpoint, setJobEndpoint,
'job/872324.json', 'job/872324.json',
mockedState, mockedState,
[{ type: types.SET_JOB_ENDPOINT, payload: 'job/872324.json' }], [{ type: types.SET_JOB_ENDPOINT, payload: 'job/872324.json' }],
[], [],
done,
); );
}); });
}); });
describe('setJobLogOptions', () => { describe('setJobLogOptions', () => {
it('should commit SET_JOB_LOG_OPTIONS mutation', (done) => { it('should commit SET_JOB_LOG_OPTIONS mutation', () => {
testAction( return testAction(
setJobLogOptions, setJobLogOptions,
{ pagePath: 'job/872324/trace.json' }, { pagePath: 'job/872324/trace.json' },
mockedState, mockedState,
[{ type: types.SET_JOB_LOG_OPTIONS, payload: { pagePath: 'job/872324/trace.json' } }], [{ type: types.SET_JOB_LOG_OPTIONS, payload: { pagePath: 'job/872324/trace.json' } }],
[], [],
done,
); );
}); });
}); });
describe('hideSidebar', () => { describe('hideSidebar', () => {
it('should commit HIDE_SIDEBAR mutation', (done) => { it('should commit HIDE_SIDEBAR mutation', () => {
testAction(hideSidebar, null, mockedState, [{ type: types.HIDE_SIDEBAR }], [], done); return testAction(hideSidebar, null, mockedState, [{ type: types.HIDE_SIDEBAR }], []);
}); });
}); });
describe('showSidebar', () => { describe('showSidebar', () => {
it('should commit HIDE_SIDEBAR mutation', (done) => { it('should commit SHOW_SIDEBAR mutation', () => {
testAction(showSidebar, null, mockedState, [{ type: types.SHOW_SIDEBAR }], [], done); return testAction(showSidebar, null, mockedState, [{ type: types.SHOW_SIDEBAR }], []);
}); });
}); });
describe('toggleSidebar', () => { describe('toggleSidebar', () => {
describe('when isSidebarOpen is true', () => { describe('when isSidebarOpen is true', () => {
it('should dispatch hideSidebar', (done) => { it('should dispatch hideSidebar', () => {
testAction(toggleSidebar, null, mockedState, [], [{ type: 'hideSidebar' }], done); return testAction(toggleSidebar, null, mockedState, [], [{ type: 'hideSidebar' }]);
}); });
}); });
describe('when isSidebarOpen is false', () => { describe('when isSidebarOpen is false', () => {
it('should dispatch showSidebar', (done) => { it('should dispatch showSidebar', () => {
mockedState.isSidebarOpen = false; mockedState.isSidebarOpen = false;
testAction(toggleSidebar, null, mockedState, [], [{ type: 'showSidebar' }], done); return testAction(toggleSidebar, null, mockedState, [], [{ type: 'showSidebar' }]);
}); });
}); });
}); });
describe('requestJob', () => { describe('requestJob', () => {
it('should commit REQUEST_JOB mutation', (done) => { it('should commit REQUEST_JOB mutation', () => {
testAction(requestJob, null, mockedState, [{ type: types.REQUEST_JOB }], [], done); return testAction(requestJob, null, mockedState, [{ type: types.REQUEST_JOB }], []);
}); });
}); });
...@@ -113,10 +111,10 @@ describe('Job State actions', () => { ...@@ -113,10 +111,10 @@ describe('Job State actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestJob and receiveJobSuccess ', (done) => { it('dispatches requestJob and receiveJobSuccess ', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`).replyOnce(200, { id: 121212, name: 'karma' }); mock.onGet(`${TEST_HOST}/endpoint.json`).replyOnce(200, { id: 121212, name: 'karma' });
testAction( return testAction(
fetchJob, fetchJob,
null, null,
mockedState, mockedState,
...@@ -130,7 +128,6 @@ describe('Job State actions', () => { ...@@ -130,7 +128,6 @@ describe('Job State actions', () => {
type: 'receiveJobSuccess', type: 'receiveJobSuccess',
}, },
], ],
done,
); );
}); });
}); });
...@@ -140,8 +137,8 @@ describe('Job State actions', () => { ...@@ -140,8 +137,8 @@ describe('Job State actions', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`).reply(500); mock.onGet(`${TEST_HOST}/endpoint.json`).reply(500);
}); });
it('dispatches requestJob and receiveJobError ', (done) => { it('dispatches requestJob and receiveJobError ', () => {
testAction( return testAction(
fetchJob, fetchJob,
null, null,
mockedState, mockedState,
...@@ -154,46 +151,50 @@ describe('Job State actions', () => { ...@@ -154,46 +151,50 @@ describe('Job State actions', () => {
type: 'receiveJobError', type: 'receiveJobError',
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('receiveJobSuccess', () => { describe('receiveJobSuccess', () => {
it('should commit RECEIVE_JOB_SUCCESS mutation', (done) => { it('should commit RECEIVE_JOB_SUCCESS mutation', () => {
testAction( return testAction(
receiveJobSuccess, receiveJobSuccess,
{ id: 121232132 }, { id: 121232132 },
mockedState, mockedState,
[{ type: types.RECEIVE_JOB_SUCCESS, payload: { id: 121232132 } }], [{ type: types.RECEIVE_JOB_SUCCESS, payload: { id: 121232132 } }],
[], [],
done,
); );
}); });
}); });
describe('receiveJobError', () => { describe('receiveJobError', () => {
it('should commit RECEIVE_JOB_ERROR mutation', (done) => { it('should commit RECEIVE_JOB_ERROR mutation', () => {
testAction(receiveJobError, null, mockedState, [{ type: types.RECEIVE_JOB_ERROR }], [], done); return testAction(
receiveJobError,
null,
mockedState,
[{ type: types.RECEIVE_JOB_ERROR }],
[],
);
}); });
}); });
describe('scrollTop', () => { describe('scrollTop', () => {
it('should dispatch toggleScrollButtons action', (done) => { it('should dispatch toggleScrollButtons action', () => {
testAction(scrollTop, null, mockedState, [], [{ type: 'toggleScrollButtons' }], done); return testAction(scrollTop, null, mockedState, [], [{ type: 'toggleScrollButtons' }]);
}); });
}); });
describe('scrollBottom', () => { describe('scrollBottom', () => {
it('should dispatch toggleScrollButtons action', (done) => { it('should dispatch toggleScrollButtons action', () => {
testAction(scrollBottom, null, mockedState, [], [{ type: 'toggleScrollButtons' }], done); return testAction(scrollBottom, null, mockedState, [], [{ type: 'toggleScrollButtons' }]);
}); });
}); });
describe('requestJobLog', () => { describe('requestJobLog', () => {
it('should commit REQUEST_JOB_LOG mutation', (done) => { it('should commit REQUEST_JOB_LOG mutation', () => {
testAction(requestJobLog, null, mockedState, [{ type: types.REQUEST_JOB_LOG }], [], done); return testAction(requestJobLog, null, mockedState, [{ type: types.REQUEST_JOB_LOG }], []);
}); });
}); });
...@@ -212,13 +213,13 @@ describe('Job State actions', () => { ...@@ -212,13 +213,13 @@ describe('Job State actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestJobLog, receiveJobLogSuccess and stopPollingJobLog when job is complete', (done) => { it('dispatches requestJobLog, receiveJobLogSuccess and stopPollingJobLog when job is complete', () => {
mock.onGet(`${TEST_HOST}/endpoint/trace.json`).replyOnce(200, { mock.onGet(`${TEST_HOST}/endpoint/trace.json`).replyOnce(200, {
html: 'I, [2018-08-17T22:57:45.707325 #1841] INFO -- :', html: 'I, [2018-08-17T22:57:45.707325 #1841] INFO -- :',
complete: true, complete: true,
}); });
testAction( return testAction(
fetchJobLog, fetchJobLog,
null, null,
mockedState, mockedState,
...@@ -239,7 +240,6 @@ describe('Job State actions', () => { ...@@ -239,7 +240,6 @@ describe('Job State actions', () => {
type: 'stopPollingJobLog', type: 'stopPollingJobLog',
}, },
], ],
done,
); );
}); });
...@@ -255,8 +255,8 @@ describe('Job State actions', () => { ...@@ -255,8 +255,8 @@ describe('Job State actions', () => {
mock.onGet(`${TEST_HOST}/endpoint/trace.json`).replyOnce(200, jobLogPayload); mock.onGet(`${TEST_HOST}/endpoint/trace.json`).replyOnce(200, jobLogPayload);
}); });
it('dispatches startPollingJobLog', (done) => { it('dispatches startPollingJobLog', () => {
testAction( return testAction(
fetchJobLog, fetchJobLog,
null, null,
mockedState, mockedState,
...@@ -266,14 +266,13 @@ describe('Job State actions', () => { ...@@ -266,14 +266,13 @@ describe('Job State actions', () => {
{ type: 'receiveJobLogSuccess', payload: jobLogPayload }, { type: 'receiveJobLogSuccess', payload: jobLogPayload },
{ type: 'startPollingJobLog' }, { type: 'startPollingJobLog' },
], ],
done,
); );
}); });
it('does not dispatch startPollingJobLog when timeout is non-empty', (done) => { it('does not dispatch startPollingJobLog when timeout is non-empty', () => {
mockedState.jobLogTimeout = 1; mockedState.jobLogTimeout = 1;
testAction( return testAction(
fetchJobLog, fetchJobLog,
null, null,
mockedState, mockedState,
...@@ -282,7 +281,6 @@ describe('Job State actions', () => { ...@@ -282,7 +281,6 @@ describe('Job State actions', () => {
{ type: 'toggleScrollisInBottom', payload: true }, { type: 'toggleScrollisInBottom', payload: true },
{ type: 'receiveJobLogSuccess', payload: jobLogPayload }, { type: 'receiveJobLogSuccess', payload: jobLogPayload },
], ],
done,
); );
}); });
}); });
...@@ -293,8 +291,8 @@ describe('Job State actions', () => { ...@@ -293,8 +291,8 @@ describe('Job State actions', () => {
mock.onGet(`${TEST_HOST}/endpoint/trace.json`).reply(500); mock.onGet(`${TEST_HOST}/endpoint/trace.json`).reply(500);
}); });
it('dispatches requestJobLog and receiveJobLogError ', (done) => { it('dispatches requestJobLog and receiveJobLogError ', () => {
testAction( return testAction(
fetchJobLog, fetchJobLog,
null, null,
mockedState, mockedState,
...@@ -304,7 +302,6 @@ describe('Job State actions', () => { ...@@ -304,7 +302,6 @@ describe('Job State actions', () => {
type: 'receiveJobLogError', type: 'receiveJobLogError',
}, },
], ],
done,
); );
}); });
}); });
...@@ -358,65 +355,58 @@ describe('Job State actions', () => { ...@@ -358,65 +355,58 @@ describe('Job State actions', () => {
window.clearTimeout = origTimeout; window.clearTimeout = origTimeout;
}); });
it('should commit STOP_POLLING_JOB_LOG mutation ', (done) => { it('should commit STOP_POLLING_JOB_LOG mutation ', async () => {
const jobLogTimeout = 7; const jobLogTimeout = 7;
testAction( await testAction(
stopPollingJobLog, stopPollingJobLog,
null, null,
{ ...mockedState, jobLogTimeout }, { ...mockedState, jobLogTimeout },
[{ type: types.SET_JOB_LOG_TIMEOUT, payload: 0 }, { type: types.STOP_POLLING_JOB_LOG }], [{ type: types.SET_JOB_LOG_TIMEOUT, payload: 0 }, { type: types.STOP_POLLING_JOB_LOG }],
[], [],
) );
.then(() => {
expect(window.clearTimeout).toHaveBeenCalledWith(jobLogTimeout); expect(window.clearTimeout).toHaveBeenCalledWith(jobLogTimeout);
})
.then(done)
.catch(done.fail);
}); });
}); });
describe('receiveJobLogSuccess', () => { describe('receiveJobLogSuccess', () => {
it('should commit RECEIVE_JOB_LOG_SUCCESS mutation ', (done) => { it('should commit RECEIVE_JOB_LOG_SUCCESS mutation ', () => {
testAction( return testAction(
receiveJobLogSuccess, receiveJobLogSuccess,
'hello world', 'hello world',
mockedState, mockedState,
[{ type: types.RECEIVE_JOB_LOG_SUCCESS, payload: 'hello world' }], [{ type: types.RECEIVE_JOB_LOG_SUCCESS, payload: 'hello world' }],
[], [],
done,
); );
}); });
}); });
describe('receiveJobLogError', () => { describe('receiveJobLogError', () => {
it('should commit stop polling job log', (done) => { it('should commit stop polling job log', () => {
testAction(receiveJobLogError, null, mockedState, [], [{ type: 'stopPollingJobLog' }], done); return testAction(receiveJobLogError, null, mockedState, [], [{ type: 'stopPollingJobLog' }]);
}); });
}); });
describe('toggleCollapsibleLine', () => { describe('toggleCollapsibleLine', () => {
it('should commit TOGGLE_COLLAPSIBLE_LINE mutation ', (done) => { it('should commit TOGGLE_COLLAPSIBLE_LINE mutation ', () => {
testAction( return testAction(
toggleCollapsibleLine, toggleCollapsibleLine,
{ isClosed: true }, { isClosed: true },
mockedState, mockedState,
[{ type: types.TOGGLE_COLLAPSIBLE_LINE, payload: { isClosed: true } }], [{ type: types.TOGGLE_COLLAPSIBLE_LINE, payload: { isClosed: true } }],
[], [],
done,
); );
}); });
}); });
describe('requestJobsForStage', () => { describe('requestJobsForStage', () => {
it('should commit REQUEST_JOBS_FOR_STAGE mutation ', (done) => { it('should commit REQUEST_JOBS_FOR_STAGE mutation ', () => {
testAction( return testAction(
requestJobsForStage, requestJobsForStage,
{ name: 'deploy' }, { name: 'deploy' },
mockedState, mockedState,
[{ type: types.REQUEST_JOBS_FOR_STAGE, payload: { name: 'deploy' } }], [{ type: types.REQUEST_JOBS_FOR_STAGE, payload: { name: 'deploy' } }],
[], [],
done,
); );
}); });
}); });
...@@ -433,12 +423,12 @@ describe('Job State actions', () => { ...@@ -433,12 +423,12 @@ describe('Job State actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestJobsForStage and receiveJobsForStageSuccess ', (done) => { it('dispatches requestJobsForStage and receiveJobsForStageSuccess ', () => {
mock mock
.onGet(`${TEST_HOST}/jobs.json`) .onGet(`${TEST_HOST}/jobs.json`)
.replyOnce(200, { latest_statuses: [{ id: 121212, name: 'build' }], retried: [] }); .replyOnce(200, { latest_statuses: [{ id: 121212, name: 'build' }], retried: [] });
testAction( return testAction(
fetchJobsForStage, fetchJobsForStage,
{ dropdown_path: `${TEST_HOST}/jobs.json` }, { dropdown_path: `${TEST_HOST}/jobs.json` },
mockedState, mockedState,
...@@ -453,7 +443,6 @@ describe('Job State actions', () => { ...@@ -453,7 +443,6 @@ describe('Job State actions', () => {
type: 'receiveJobsForStageSuccess', type: 'receiveJobsForStageSuccess',
}, },
], ],
done,
); );
}); });
}); });
...@@ -463,8 +452,8 @@ describe('Job State actions', () => { ...@@ -463,8 +452,8 @@ describe('Job State actions', () => {
mock.onGet(`${TEST_HOST}/jobs.json`).reply(500); mock.onGet(`${TEST_HOST}/jobs.json`).reply(500);
}); });
it('dispatches requestJobsForStage and receiveJobsForStageError', (done) => { it('dispatches requestJobsForStage and receiveJobsForStageError', () => {
testAction( return testAction(
fetchJobsForStage, fetchJobsForStage,
{ dropdown_path: `${TEST_HOST}/jobs.json` }, { dropdown_path: `${TEST_HOST}/jobs.json` },
mockedState, mockedState,
...@@ -478,34 +467,31 @@ describe('Job State actions', () => { ...@@ -478,34 +467,31 @@ describe('Job State actions', () => {
type: 'receiveJobsForStageError', type: 'receiveJobsForStageError',
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('receiveJobsForStageSuccess', () => { describe('receiveJobsForStageSuccess', () => {
it('should commit RECEIVE_JOBS_FOR_STAGE_SUCCESS mutation ', (done) => { it('should commit RECEIVE_JOBS_FOR_STAGE_SUCCESS mutation ', () => {
testAction( return testAction(
receiveJobsForStageSuccess, receiveJobsForStageSuccess,
[{ id: 121212, name: 'karma' }], [{ id: 121212, name: 'karma' }],
mockedState, mockedState,
[{ type: types.RECEIVE_JOBS_FOR_STAGE_SUCCESS, payload: [{ id: 121212, name: 'karma' }] }], [{ type: types.RECEIVE_JOBS_FOR_STAGE_SUCCESS, payload: [{ id: 121212, name: 'karma' }] }],
[], [],
done,
); );
}); });
}); });
describe('receiveJobsForStageError', () => { describe('receiveJobsForStageError', () => {
it('should commit RECEIVE_JOBS_FOR_STAGE_ERROR mutation ', (done) => { it('should commit RECEIVE_JOBS_FOR_STAGE_ERROR mutation ', () => {
testAction( return testAction(
receiveJobsForStageError, receiveJobsForStageError,
null, null,
mockedState, mockedState,
[{ type: types.RECEIVE_JOBS_FOR_STAGE_ERROR }], [{ type: types.RECEIVE_JOBS_FOR_STAGE_ERROR }],
[], [],
done,
); );
}); });
}); });
......
...@@ -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);
return new Promise((resolve) => {
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
debouncedSpy(); debouncedSpy();
debouncedSpy(); debouncedSpy();
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledTimes(1);
done(); 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,17 +405,15 @@ describe('common_utils', () => { ...@@ -406,17 +405,15 @@ 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();
...@@ -424,21 +421,18 @@ describe('common_utils', () => { ...@@ -424,21 +421,18 @@ describe('common_utils', () => {
} 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({ expect(createFlash).toHaveBeenCalledWith({
message: 'Failed to save merge conflicts resolutions. Please try again!', message: 'Failed to save merge conflicts resolutions. Please try again!',
}); });
done();
},
);
}); });
}); });
...@@ -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, { expect(Cookies.set).toHaveBeenCalledWith('diff_view', payload, {
expires: 365, expires: 365,
secure: false, secure: false,
}); });
done();
},
);
}); });
}); });
...@@ -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(error).toBe(dummyError);
expect(redirectTo).not.toHaveBeenCalled(); expect(redirectTo).not.toHaveBeenCalled();
expect(eventHub.$emit).toHaveBeenCalledWith('deleteMilestoneModal.requestFinished', { expect(eventHub.$emit).toHaveBeenCalledWith('deleteMilestoneModal.requestFinished', {
milestoneUrl: props.milestoneUrl, milestoneUrl: props.milestoneUrl,
successful: false, 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(() => {
......
...@@ -88,8 +88,8 @@ describe('Monitoring store actions', () => { ...@@ -88,8 +88,8 @@ describe('Monitoring store actions', () => {
// Setup // Setup
describe('setGettingStartedEmptyState', () => { describe('setGettingStartedEmptyState', () => {
it('should commit SET_GETTING_STARTED_EMPTY_STATE mutation', (done) => { it('should commit SET_GETTING_STARTED_EMPTY_STATE mutation', () => {
testAction( return testAction(
setGettingStartedEmptyState, setGettingStartedEmptyState,
null, null,
state, state,
...@@ -99,14 +99,13 @@ describe('Monitoring store actions', () => { ...@@ -99,14 +99,13 @@ describe('Monitoring store actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('setInitialState', () => { describe('setInitialState', () => {
it('should commit SET_INITIAL_STATE mutation', (done) => { it('should commit SET_INITIAL_STATE mutation', () => {
testAction( return testAction(
setInitialState, setInitialState,
{ {
currentDashboard: '.gitlab/dashboards/dashboard.yml', currentDashboard: '.gitlab/dashboards/dashboard.yml',
...@@ -123,7 +122,6 @@ describe('Monitoring store actions', () => { ...@@ -123,7 +122,6 @@ describe('Monitoring store actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -233,9 +231,8 @@ describe('Monitoring store actions', () => { ...@@ -233,9 +231,8 @@ describe('Monitoring store actions', () => {
}; };
}); });
it('dispatches a failure', (done) => { it('dispatches a failure', async () => {
result() await result();
.then(() => {
expect(commit).toHaveBeenCalledWith( expect(commit).toHaveBeenCalledWith(
types.SET_ALL_DASHBOARDS, types.SET_ALL_DASHBOARDS,
mockDashboardsErrorResponse.all_dashboards, mockDashboardsErrorResponse.all_dashboards,
...@@ -245,14 +242,10 @@ describe('Monitoring store actions', () => { ...@@ -245,14 +242,10 @@ describe('Monitoring store actions', () => {
new Error('Request failed with status code 500'), new Error('Request failed with status code 500'),
); );
expect(createFlash).toHaveBeenCalled(); expect(createFlash).toHaveBeenCalled();
done();
})
.catch(done.fail);
}); });
it('dispatches a failure action when a message is returned', (done) => { it('dispatches a failure action when a message is returned', async () => {
result() await result();
.then(() => {
expect(dispatch).toHaveBeenCalledWith( expect(dispatch).toHaveBeenCalledWith(
'receiveMetricsDashboardFailure', 'receiveMetricsDashboardFailure',
new Error('Request failed with status code 500'), new Error('Request failed with status code 500'),
...@@ -260,24 +253,17 @@ describe('Monitoring store actions', () => { ...@@ -260,24 +253,17 @@ describe('Monitoring store actions', () => {
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: expect.stringContaining(mockDashboardsErrorResponse.message), message: expect.stringContaining(mockDashboardsErrorResponse.message),
}); });
done();
})
.catch(done.fail);
}); });
it('does not show a flash error when showErrorBanner is disabled', (done) => { it('does not show a flash error when showErrorBanner is disabled', async () => {
state.showErrorBanner = false; state.showErrorBanner = false;
result() await result();
.then(() => {
expect(dispatch).toHaveBeenCalledWith( expect(dispatch).toHaveBeenCalledWith(
'receiveMetricsDashboardFailure', 'receiveMetricsDashboardFailure',
new Error('Request failed with status code 500'), new Error('Request failed with status code 500'),
); );
expect(createFlash).not.toHaveBeenCalled(); expect(createFlash).not.toHaveBeenCalled();
done();
})
.catch(done.fail);
}); });
}); });
}); });
...@@ -322,21 +308,16 @@ describe('Monitoring store actions', () => { ...@@ -322,21 +308,16 @@ describe('Monitoring store actions', () => {
state.timeRange = defaultTimeRange; state.timeRange = defaultTimeRange;
}); });
it('commits empty state when state.groups is empty', (done) => { it('commits empty state when state.groups is empty', async () => {
const localGetters = { const localGetters = {
metricsWithData: () => [], metricsWithData: () => [],
}; };
fetchDashboardData({ state, commit, dispatch, getters: localGetters }) await fetchDashboardData({ state, commit, dispatch, getters: localGetters });
.then(() => { expect(Tracking.event).toHaveBeenCalledWith(document.body.dataset.page, 'dashboard_fetch', {
expect(Tracking.event).toHaveBeenCalledWith(
document.body.dataset.page,
'dashboard_fetch',
{
label: 'custom_metrics_dashboard', label: 'custom_metrics_dashboard',
property: 'count', property: 'count',
value: 0, value: 0,
}, });
);
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenCalledWith('fetchDeploymentsData'); expect(dispatch).toHaveBeenCalledWith('fetchDeploymentsData');
expect(dispatch).toHaveBeenCalledWith('fetchVariableMetricLabelValues', { expect(dispatch).toHaveBeenCalledWith('fetchVariableMetricLabelValues', {
...@@ -348,12 +329,9 @@ describe('Monitoring store actions', () => { ...@@ -348,12 +329,9 @@ describe('Monitoring store actions', () => {
}); });
expect(createFlash).not.toHaveBeenCalled(); expect(createFlash).not.toHaveBeenCalled();
done();
})
.catch(done.fail);
}); });
it('dispatches fetchPrometheusMetric for each panel query', (done) => { it('dispatches fetchPrometheusMetric for each panel query', async () => {
state.dashboard.panelGroups = convertObjectPropsToCamelCase( state.dashboard.panelGroups = convertObjectPropsToCamelCase(
metricsDashboardResponse.dashboard.panel_groups, metricsDashboardResponse.dashboard.panel_groups,
); );
...@@ -363,8 +341,7 @@ describe('Monitoring store actions', () => { ...@@ -363,8 +341,7 @@ describe('Monitoring store actions', () => {
metricsWithData: () => [metric.id], metricsWithData: () => [metric.id],
}; };
fetchDashboardData({ state, commit, dispatch, getters: localGetters }) await fetchDashboardData({ state, commit, dispatch, getters: localGetters });
.then(() => {
expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetric', { expect(dispatch).toHaveBeenCalledWith('fetchPrometheusMetric', {
metric, metric,
defaultQueryParams: { defaultQueryParams: {
...@@ -374,23 +351,14 @@ describe('Monitoring store actions', () => { ...@@ -374,23 +351,14 @@ describe('Monitoring store actions', () => {
}, },
}); });
expect(Tracking.event).toHaveBeenCalledWith( expect(Tracking.event).toHaveBeenCalledWith(document.body.dataset.page, 'dashboard_fetch', {
document.body.dataset.page,
'dashboard_fetch',
{
label: 'custom_metrics_dashboard', label: 'custom_metrics_dashboard',
property: 'count', property: 'count',
value: 1, value: 1,
}, });
);
done();
})
.catch(done.fail);
done();
}); });
it('dispatches fetchPrometheusMetric for each panel query, handles an error', (done) => { it('dispatches fetchPrometheusMetric for each panel query, handles an error', async () => {
state.dashboard.panelGroups = metricsDashboardViewModel.panelGroups; state.dashboard.panelGroups = metricsDashboardViewModel.panelGroups;
const metric = state.dashboard.panelGroups[0].panels[0].metrics[0]; const metric = state.dashboard.panelGroups[0].panels[0].metrics[0];
...@@ -400,8 +368,7 @@ describe('Monitoring store actions', () => { ...@@ -400,8 +368,7 @@ describe('Monitoring store actions', () => {
dispatch.mockRejectedValueOnce(new Error('Error fetching this metric')); dispatch.mockRejectedValueOnce(new Error('Error fetching this metric'));
dispatch.mockResolvedValue(); dispatch.mockResolvedValue();
fetchDashboardData({ state, commit, dispatch }) await fetchDashboardData({ state, commit, dispatch });
.then(() => {
const defaultQueryParams = { const defaultQueryParams = {
start_time: expect.any(String), start_time: expect.any(String),
end_time: expect.any(String), end_time: expect.any(String),
...@@ -419,11 +386,6 @@ describe('Monitoring store actions', () => { ...@@ -419,11 +386,6 @@ describe('Monitoring store actions', () => {
}); });
expect(createFlash).toHaveBeenCalledTimes(1); expect(createFlash).toHaveBeenCalledTimes(1);
done();
})
.catch(done.fail);
done();
}); });
}); });
...@@ -449,10 +411,10 @@ describe('Monitoring store actions', () => { ...@@ -449,10 +411,10 @@ describe('Monitoring store actions', () => {
}; };
}); });
it('commits result', (done) => { it('commits result', () => {
mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt
testAction( return testAction(
fetchPrometheusMetric, fetchPrometheusMetric,
{ metric, defaultQueryParams }, { metric, defaultQueryParams },
state, state,
...@@ -472,10 +434,7 @@ describe('Monitoring store actions', () => { ...@@ -472,10 +434,7 @@ describe('Monitoring store actions', () => {
}, },
], ],
[], [],
() => { );
done();
},
).catch(done.fail);
}); });
describe('without metric defined step', () => { describe('without metric defined step', () => {
...@@ -485,10 +444,10 @@ describe('Monitoring store actions', () => { ...@@ -485,10 +444,10 @@ describe('Monitoring store actions', () => {
step: 60, step: 60,
}; };
it('uses calculated step', (done) => { it('uses calculated step', async () => {
mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt
testAction( await testAction(
fetchPrometheusMetric, fetchPrometheusMetric,
{ metric, defaultQueryParams }, { metric, defaultQueryParams },
state, state,
...@@ -508,11 +467,8 @@ describe('Monitoring store actions', () => { ...@@ -508,11 +467,8 @@ describe('Monitoring store actions', () => {
}, },
], ],
[], [],
() => { );
expect(mock.history.get[0].params).toEqual(expectedParams); expect(mock.history.get[0].params).toEqual(expectedParams);
done();
},
).catch(done.fail);
}); });
}); });
...@@ -527,10 +483,10 @@ describe('Monitoring store actions', () => { ...@@ -527,10 +483,10 @@ describe('Monitoring store actions', () => {
step: 7, step: 7,
}; };
it('uses metric step', (done) => { it('uses metric step', async () => {
mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt mock.onGet(prometheusEndpointPath).reply(200, { data }); // One attempt
testAction( await testAction(
fetchPrometheusMetric, fetchPrometheusMetric,
{ metric, defaultQueryParams }, { metric, defaultQueryParams },
state, state,
...@@ -550,19 +506,17 @@ describe('Monitoring store actions', () => { ...@@ -550,19 +506,17 @@ describe('Monitoring store actions', () => {
}, },
], ],
[], [],
() => { );
expect(mock.history.get[0].params).toEqual(expectedParams); expect(mock.history.get[0].params).toEqual(expectedParams);
done();
},
).catch(done.fail);
}); });
}); });
it('commits failure, when waiting for results and getting a server error', (done) => { it('commits failure, when waiting for results and getting a server error', async () => {
mock.onGet(prometheusEndpointPath).reply(500); mock.onGet(prometheusEndpointPath).reply(500);
const error = new Error('Request failed with status code 500'); const error = new Error('Request failed with status code 500');
await expect(
testAction( testAction(
fetchPrometheusMetric, fetchPrometheusMetric,
{ metric, defaultQueryParams }, { metric, defaultQueryParams },
...@@ -583,10 +537,8 @@ describe('Monitoring store actions', () => { ...@@ -583,10 +537,8 @@ describe('Monitoring store actions', () => {
}, },
], ],
[], [],
).catch((e) => { ),
expect(e).toEqual(error); ).rejects.toEqual(error);
done();
});
}); });
}); });
...@@ -991,20 +943,16 @@ describe('Monitoring store actions', () => { ...@@ -991,20 +943,16 @@ describe('Monitoring store actions', () => {
state.dashboardsEndpoint = '/dashboards.json'; state.dashboardsEndpoint = '/dashboards.json';
}); });
it('Succesful POST request resolves', (done) => { it('Succesful POST request resolves', async () => {
mock.onPost(state.dashboardsEndpoint).reply(statusCodes.CREATED, { mock.onPost(state.dashboardsEndpoint).reply(statusCodes.CREATED, {
dashboard: dashboardGitResponse[1], dashboard: dashboardGitResponse[1],
}); });
testAction(duplicateSystemDashboard, {}, state, [], []) await testAction(duplicateSystemDashboard, {}, state, [], []);
.then(() => {
expect(mock.history.post).toHaveLength(1); expect(mock.history.post).toHaveLength(1);
done();
})
.catch(done.fail);
}); });
it('Succesful POST request resolves to a dashboard', (done) => { it('Succesful POST request resolves to a dashboard', async () => {
const mockCreatedDashboard = dashboardGitResponse[1]; const mockCreatedDashboard = dashboardGitResponse[1];
const params = { const params = {
...@@ -1025,50 +973,40 @@ describe('Monitoring store actions', () => { ...@@ -1025,50 +973,40 @@ describe('Monitoring store actions', () => {
dashboard: mockCreatedDashboard, dashboard: mockCreatedDashboard,
}); });
testAction(duplicateSystemDashboard, params, state, [], []) const result = await testAction(duplicateSystemDashboard, params, state, [], []);
.then((result) => {
expect(mock.history.post).toHaveLength(1); expect(mock.history.post).toHaveLength(1);
expect(mock.history.post[0].data).toEqual(expectedPayload); expect(mock.history.post[0].data).toEqual(expectedPayload);
expect(result).toEqual(mockCreatedDashboard); expect(result).toEqual(mockCreatedDashboard);
done();
})
.catch(done.fail);
}); });
it('Failed POST request throws an error', (done) => { it('Failed POST request throws an error', async () => {
mock.onPost(state.dashboardsEndpoint).reply(statusCodes.BAD_REQUEST); mock.onPost(state.dashboardsEndpoint).reply(statusCodes.BAD_REQUEST);
testAction(duplicateSystemDashboard, {}, state, [], []).catch((err) => { await expect(testAction(duplicateSystemDashboard, {}, state, [], [])).rejects.toEqual(
'There was an error creating the dashboard.',
);
expect(mock.history.post).toHaveLength(1); expect(mock.history.post).toHaveLength(1);
expect(err).toEqual(expect.any(String));
done();
});
}); });
it('Failed POST request throws an error with a description', (done) => { it('Failed POST request throws an error with a description', async () => {
const backendErrorMsg = 'This file already exists!'; const backendErrorMsg = 'This file already exists!';
mock.onPost(state.dashboardsEndpoint).reply(statusCodes.BAD_REQUEST, { mock.onPost(state.dashboardsEndpoint).reply(statusCodes.BAD_REQUEST, {
error: backendErrorMsg, error: backendErrorMsg,
}); });
testAction(duplicateSystemDashboard, {}, state, [], []).catch((err) => { await expect(testAction(duplicateSystemDashboard, {}, state, [], [])).rejects.toEqual(
`There was an error creating the dashboard. ${backendErrorMsg}`,
);
expect(mock.history.post).toHaveLength(1); expect(mock.history.post).toHaveLength(1);
expect(err).toEqual(expect.any(String));
expect(err).toEqual(expect.stringContaining(backendErrorMsg));
done();
});
}); });
}); });
// Variables manipulation // Variables manipulation
describe('updateVariablesAndFetchData', () => { describe('updateVariablesAndFetchData', () => {
it('should commit UPDATE_VARIABLE_VALUE mutation and fetch data', (done) => { it('should commit UPDATE_VARIABLE_VALUE mutation and fetch data', () => {
testAction( return testAction(
updateVariablesAndFetchData, updateVariablesAndFetchData,
{ pod: 'POD' }, { pod: 'POD' },
state, state,
...@@ -1083,7 +1021,6 @@ describe('Monitoring store actions', () => { ...@@ -1083,7 +1021,6 @@ describe('Monitoring store actions', () => {
type: 'fetchDashboardData', type: 'fetchDashboardData',
}, },
], ],
done,
); );
}); });
}); });
......
...@@ -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)
.then(() => {
expect($submitButton).not.toBeDisabled(); expect($submitButton).not.toBeDisabled();
})
.then(done)
.catch(done.fail);
}); });
}); });
......
...@@ -62,118 +62,109 @@ describe('Actions Notes Store', () => { ...@@ -62,118 +62,109 @@ describe('Actions Notes Store', () => {
}); });
describe('setNotesData', () => { describe('setNotesData', () => {
it('should set received notes data', (done) => { it('should set received notes data', () => {
testAction( return testAction(
actions.setNotesData, actions.setNotesData,
notesDataMock, notesDataMock,
{ notesData: {} }, { notesData: {} },
[{ type: 'SET_NOTES_DATA', payload: notesDataMock }], [{ type: 'SET_NOTES_DATA', payload: notesDataMock }],
[], [],
done,
); );
}); });
}); });
describe('setNoteableData', () => { describe('setNoteableData', () => {
it('should set received issue data', (done) => { it('should set received issue data', () => {
testAction( return testAction(
actions.setNoteableData, actions.setNoteableData,
noteableDataMock, noteableDataMock,
{ noteableData: {} }, { noteableData: {} },
[{ type: 'SET_NOTEABLE_DATA', payload: noteableDataMock }], [{ type: 'SET_NOTEABLE_DATA', payload: noteableDataMock }],
[], [],
done,
); );
}); });
}); });
describe('setUserData', () => { describe('setUserData', () => {
it('should set received user data', (done) => { it('should set received user data', () => {
testAction( return testAction(
actions.setUserData, actions.setUserData,
userDataMock, userDataMock,
{ userData: {} }, { userData: {} },
[{ type: 'SET_USER_DATA', payload: userDataMock }], [{ type: 'SET_USER_DATA', payload: userDataMock }],
[], [],
done,
); );
}); });
}); });
describe('setLastFetchedAt', () => { describe('setLastFetchedAt', () => {
it('should set received timestamp', (done) => { it('should set received timestamp', () => {
testAction( return testAction(
actions.setLastFetchedAt, actions.setLastFetchedAt,
'timestamp', 'timestamp',
{ lastFetchedAt: {} }, { lastFetchedAt: {} },
[{ type: 'SET_LAST_FETCHED_AT', payload: 'timestamp' }], [{ type: 'SET_LAST_FETCHED_AT', payload: 'timestamp' }],
[], [],
done,
); );
}); });
}); });
describe('setInitialNotes', () => { describe('setInitialNotes', () => {
it('should set initial notes', (done) => { it('should set initial notes', () => {
testAction( return testAction(
actions.setInitialNotes, actions.setInitialNotes,
[individualNote], [individualNote],
{ notes: [] }, { notes: [] },
[{ type: 'ADD_OR_UPDATE_DISCUSSIONS', payload: [individualNote] }], [{ type: 'ADD_OR_UPDATE_DISCUSSIONS', payload: [individualNote] }],
[], [],
done,
); );
}); });
}); });
describe('setTargetNoteHash', () => { describe('setTargetNoteHash', () => {
it('should set target note hash', (done) => { it('should set target note hash', () => {
testAction( return testAction(
actions.setTargetNoteHash, actions.setTargetNoteHash,
'hash', 'hash',
{ notes: [] }, { notes: [] },
[{ type: 'SET_TARGET_NOTE_HASH', payload: 'hash' }], [{ type: 'SET_TARGET_NOTE_HASH', payload: 'hash' }],
[], [],
done,
); );
}); });
}); });
describe('toggleDiscussion', () => { describe('toggleDiscussion', () => {
it('should toggle discussion', (done) => { it('should toggle discussion', () => {
testAction( return testAction(
actions.toggleDiscussion, actions.toggleDiscussion,
{ discussionId: discussionMock.id }, { discussionId: discussionMock.id },
{ notes: [discussionMock] }, { notes: [discussionMock] },
[{ type: 'TOGGLE_DISCUSSION', payload: { discussionId: discussionMock.id } }], [{ type: 'TOGGLE_DISCUSSION', payload: { discussionId: discussionMock.id } }],
[], [],
done,
); );
}); });
}); });
describe('expandDiscussion', () => { describe('expandDiscussion', () => {
it('should expand discussion', (done) => { it('should expand discussion', () => {
testAction( return testAction(
actions.expandDiscussion, actions.expandDiscussion,
{ discussionId: discussionMock.id }, { discussionId: discussionMock.id },
{ notes: [discussionMock] }, { notes: [discussionMock] },
[{ type: 'EXPAND_DISCUSSION', payload: { discussionId: discussionMock.id } }], [{ type: 'EXPAND_DISCUSSION', payload: { discussionId: discussionMock.id } }],
[{ type: 'diffs/renderFileForDiscussionId', payload: discussionMock.id }], [{ type: 'diffs/renderFileForDiscussionId', payload: discussionMock.id }],
done,
); );
}); });
}); });
describe('collapseDiscussion', () => { describe('collapseDiscussion', () => {
it('should commit collapse discussion', (done) => { it('should commit collapse discussion', () => {
testAction( return testAction(
actions.collapseDiscussion, actions.collapseDiscussion,
{ discussionId: discussionMock.id }, { discussionId: discussionMock.id },
{ notes: [discussionMock] }, { notes: [discussionMock] },
[{ type: 'COLLAPSE_DISCUSSION', payload: { discussionId: discussionMock.id } }], [{ type: 'COLLAPSE_DISCUSSION', payload: { discussionId: discussionMock.id } }],
[], [],
done,
); );
}); });
}); });
...@@ -184,28 +175,18 @@ describe('Actions Notes Store', () => { ...@@ -184,28 +175,18 @@ describe('Actions Notes Store', () => {
}); });
describe('closeMergeRequest', () => { describe('closeMergeRequest', () => {
it('sets state as closed', (done) => { it('sets state as closed', async () => {
store await store.dispatch('closeIssuable', { notesData: { closeIssuePath: '' } });
.dispatch('closeIssuable', { notesData: { closeIssuePath: '' } })
.then(() => {
expect(store.state.noteableData.state).toEqual('closed'); expect(store.state.noteableData.state).toEqual('closed');
expect(store.state.isToggleStateButtonLoading).toEqual(false); expect(store.state.isToggleStateButtonLoading).toEqual(false);
done();
})
.catch(done.fail);
}); });
}); });
describe('reopenMergeRequest', () => { describe('reopenMergeRequest', () => {
it('sets state as reopened', (done) => { it('sets state as reopened', async () => {
store await store.dispatch('reopenIssuable', { notesData: { reopenIssuePath: '' } });
.dispatch('reopenIssuable', { notesData: { reopenIssuePath: '' } })
.then(() => {
expect(store.state.noteableData.state).toEqual('reopened'); expect(store.state.noteableData.state).toEqual('reopened');
expect(store.state.isToggleStateButtonLoading).toEqual(false); expect(store.state.isToggleStateButtonLoading).toEqual(false);
done();
})
.catch(done.fail);
}); });
}); });
}); });
...@@ -222,42 +203,39 @@ describe('Actions Notes Store', () => { ...@@ -222,42 +203,39 @@ describe('Actions Notes Store', () => {
}); });
describe('toggleStateButtonLoading', () => { describe('toggleStateButtonLoading', () => {
it('should set loading as true', (done) => { it('should set loading as true', () => {
testAction( return testAction(
actions.toggleStateButtonLoading, actions.toggleStateButtonLoading,
true, true,
{}, {},
[{ type: 'TOGGLE_STATE_BUTTON_LOADING', payload: true }], [{ type: 'TOGGLE_STATE_BUTTON_LOADING', payload: true }],
[], [],
done,
); );
}); });
it('should set loading as false', (done) => { it('should set loading as false', () => {
testAction( return testAction(
actions.toggleStateButtonLoading, actions.toggleStateButtonLoading,
false, false,
{}, {},
[{ type: 'TOGGLE_STATE_BUTTON_LOADING', payload: false }], [{ type: 'TOGGLE_STATE_BUTTON_LOADING', payload: false }],
[], [],
done,
); );
}); });
}); });
describe('toggleIssueLocalState', () => { describe('toggleIssueLocalState', () => {
it('sets issue state as closed', (done) => { it('sets issue state as closed', () => {
testAction(actions.toggleIssueLocalState, 'closed', {}, [{ type: 'CLOSE_ISSUE' }], [], done); return testAction(actions.toggleIssueLocalState, 'closed', {}, [{ type: 'CLOSE_ISSUE' }], []);
}); });
it('sets issue state as reopened', (done) => { it('sets issue state as reopened', () => {
testAction( return testAction(
actions.toggleIssueLocalState, actions.toggleIssueLocalState,
'reopened', 'reopened',
{}, {},
[{ type: 'REOPEN_ISSUE' }], [{ type: 'REOPEN_ISSUE' }],
[], [],
done,
); );
}); });
}); });
...@@ -291,8 +269,8 @@ describe('Actions Notes Store', () => { ...@@ -291,8 +269,8 @@ describe('Actions Notes Store', () => {
return store.dispatch('stopPolling'); return store.dispatch('stopPolling');
}; };
beforeEach((done) => { beforeEach(() => {
store.dispatch('setNotesData', notesDataMock).then(done).catch(done.fail); return store.dispatch('setNotesData', notesDataMock);
}); });
afterEach(() => { afterEach(() => {
...@@ -405,14 +383,13 @@ describe('Actions Notes Store', () => { ...@@ -405,14 +383,13 @@ describe('Actions Notes Store', () => {
}); });
describe('setNotesFetchedState', () => { describe('setNotesFetchedState', () => {
it('should set notes fetched state', (done) => { it('should set notes fetched state', () => {
testAction( return testAction(
actions.setNotesFetchedState, actions.setNotesFetchedState,
true, true,
{}, {},
[{ type: 'SET_NOTES_FETCHED_STATE', payload: true }], [{ type: 'SET_NOTES_FETCHED_STATE', payload: true }],
[], [],
done,
); );
}); });
}); });
...@@ -432,10 +409,10 @@ describe('Actions Notes Store', () => { ...@@ -432,10 +409,10 @@ describe('Actions Notes Store', () => {
document.body.setAttribute('data-page', ''); document.body.setAttribute('data-page', '');
}); });
it('commits DELETE_NOTE and dispatches updateMergeRequestWidget', (done) => { it('commits DELETE_NOTE and dispatches updateMergeRequestWidget', () => {
const note = { path: endpoint, id: 1 }; const note = { path: endpoint, id: 1 };
testAction( return testAction(
actions.removeNote, actions.removeNote,
note, note,
store.state, store.state,
...@@ -453,16 +430,15 @@ describe('Actions Notes Store', () => { ...@@ -453,16 +430,15 @@ describe('Actions Notes Store', () => {
type: 'updateResolvableDiscussionsCounts', type: 'updateResolvableDiscussionsCounts',
}, },
], ],
done,
); );
}); });
it('dispatches removeDiscussionsFromDiff on merge request page', (done) => { it('dispatches removeDiscussionsFromDiff on merge request page', () => {
const note = { path: endpoint, id: 1 }; const note = { path: endpoint, id: 1 };
document.body.setAttribute('data-page', 'projects:merge_requests:show'); document.body.setAttribute('data-page', 'projects:merge_requests:show');
testAction( return testAction(
actions.removeNote, actions.removeNote,
note, note,
store.state, store.state,
...@@ -483,7 +459,6 @@ describe('Actions Notes Store', () => { ...@@ -483,7 +459,6 @@ describe('Actions Notes Store', () => {
type: 'diffs/removeDiscussionsFromDiff', type: 'diffs/removeDiscussionsFromDiff',
}, },
], ],
done,
); );
}); });
}); });
...@@ -503,10 +478,10 @@ describe('Actions Notes Store', () => { ...@@ -503,10 +478,10 @@ describe('Actions Notes Store', () => {
document.body.setAttribute('data-page', ''); document.body.setAttribute('data-page', '');
}); });
it('dispatches removeNote', (done) => { it('dispatches removeNote', () => {
const note = { path: endpoint, id: 1 }; const note = { path: endpoint, id: 1 };
testAction( return testAction(
actions.deleteNote, actions.deleteNote,
note, note,
{}, {},
...@@ -520,7 +495,6 @@ describe('Actions Notes Store', () => { ...@@ -520,7 +495,6 @@ describe('Actions Notes Store', () => {
}, },
}, },
], ],
done,
); );
}); });
}); });
...@@ -536,8 +510,8 @@ describe('Actions Notes Store', () => { ...@@ -536,8 +510,8 @@ describe('Actions Notes Store', () => {
axiosMock.onAny().reply(200, res); axiosMock.onAny().reply(200, res);
}); });
it('commits ADD_NEW_NOTE and dispatches updateMergeRequestWidget', (done) => { it('commits ADD_NEW_NOTE and dispatches updateMergeRequestWidget', () => {
testAction( return testAction(
actions.createNewNote, actions.createNewNote,
{ endpoint: `${TEST_HOST}`, data: {} }, { endpoint: `${TEST_HOST}`, data: {} },
store.state, store.state,
...@@ -558,7 +532,6 @@ describe('Actions Notes Store', () => { ...@@ -558,7 +532,6 @@ describe('Actions Notes Store', () => {
type: 'updateResolvableDiscussionsCounts', type: 'updateResolvableDiscussionsCounts',
}, },
], ],
done,
); );
}); });
}); });
...@@ -572,14 +545,13 @@ describe('Actions Notes Store', () => { ...@@ -572,14 +545,13 @@ describe('Actions Notes Store', () => {
axiosMock.onAny().replyOnce(200, res); axiosMock.onAny().replyOnce(200, res);
}); });
it('does not commit ADD_NEW_NOTE or dispatch updateMergeRequestWidget', (done) => { it('does not commit ADD_NEW_NOTE or dispatch updateMergeRequestWidget', () => {
testAction( return testAction(
actions.createNewNote, actions.createNewNote,
{ endpoint: `${TEST_HOST}`, data: {} }, { endpoint: `${TEST_HOST}`, data: {} },
store.state, store.state,
[], [],
[], [],
done,
); );
}); });
}); });
...@@ -595,8 +567,8 @@ describe('Actions Notes Store', () => { ...@@ -595,8 +567,8 @@ describe('Actions Notes Store', () => {
}); });
describe('as note', () => { describe('as note', () => {
it('commits UPDATE_NOTE and dispatches updateMergeRequestWidget', (done) => { it('commits UPDATE_NOTE and dispatches updateMergeRequestWidget', () => {
testAction( return testAction(
actions.toggleResolveNote, actions.toggleResolveNote,
{ endpoint: `${TEST_HOST}`, isResolved: true, discussion: false }, { endpoint: `${TEST_HOST}`, isResolved: true, discussion: false },
store.state, store.state,
...@@ -614,14 +586,13 @@ describe('Actions Notes Store', () => { ...@@ -614,14 +586,13 @@ describe('Actions Notes Store', () => {
type: 'updateMergeRequestWidget', type: 'updateMergeRequestWidget',
}, },
], ],
done,
); );
}); });
}); });
describe('as discussion', () => { describe('as discussion', () => {
it('commits UPDATE_DISCUSSION and dispatches updateMergeRequestWidget', (done) => { it('commits UPDATE_DISCUSSION and dispatches updateMergeRequestWidget', () => {
testAction( return testAction(
actions.toggleResolveNote, actions.toggleResolveNote,
{ endpoint: `${TEST_HOST}`, isResolved: true, discussion: true }, { endpoint: `${TEST_HOST}`, isResolved: true, discussion: true },
store.state, store.state,
...@@ -639,7 +610,6 @@ describe('Actions Notes Store', () => { ...@@ -639,7 +610,6 @@ describe('Actions Notes Store', () => {
type: 'updateMergeRequestWidget', type: 'updateMergeRequestWidget',
}, },
], ],
done,
); );
}); });
}); });
...@@ -656,41 +626,38 @@ describe('Actions Notes Store', () => { ...@@ -656,41 +626,38 @@ describe('Actions Notes Store', () => {
}); });
describe('setCommentsDisabled', () => { describe('setCommentsDisabled', () => {
it('should set comments disabled state', (done) => { it('should set comments disabled state', () => {
testAction( return testAction(
actions.setCommentsDisabled, actions.setCommentsDisabled,
true, true,
null, null,
[{ type: 'DISABLE_COMMENTS', payload: true }], [{ type: 'DISABLE_COMMENTS', payload: true }],
[], [],
done,
); );
}); });
}); });
describe('updateResolvableDiscussionsCounts', () => { describe('updateResolvableDiscussionsCounts', () => {
it('commits UPDATE_RESOLVABLE_DISCUSSIONS_COUNTS', (done) => { it('commits UPDATE_RESOLVABLE_DISCUSSIONS_COUNTS', () => {
testAction( return testAction(
actions.updateResolvableDiscussionsCounts, actions.updateResolvableDiscussionsCounts,
null, null,
{}, {},
[{ type: 'UPDATE_RESOLVABLE_DISCUSSIONS_COUNTS' }], [{ type: 'UPDATE_RESOLVABLE_DISCUSSIONS_COUNTS' }],
[], [],
done,
); );
}); });
}); });
describe('convertToDiscussion', () => { describe('convertToDiscussion', () => {
it('commits CONVERT_TO_DISCUSSION with noteId', (done) => { it('commits CONVERT_TO_DISCUSSION with noteId', () => {
const noteId = 'dummy-note-id'; const noteId = 'dummy-note-id';
testAction( return testAction(
actions.convertToDiscussion, actions.convertToDiscussion,
noteId, noteId,
{}, {},
[{ type: 'CONVERT_TO_DISCUSSION', payload: noteId }], [{ type: 'CONVERT_TO_DISCUSSION', payload: noteId }],
[], [],
done,
); );
}); });
}); });
...@@ -786,11 +753,11 @@ describe('Actions Notes Store', () => { ...@@ -786,11 +753,11 @@ describe('Actions Notes Store', () => {
describe('replyToDiscussion', () => { describe('replyToDiscussion', () => {
const payload = { endpoint: TEST_HOST, data: {} }; const payload = { endpoint: TEST_HOST, data: {} };
it('updates discussion if response contains disussion', (done) => { it('updates discussion if response contains disussion', () => {
const discussion = { notes: [] }; const discussion = { notes: [] };
axiosMock.onAny().reply(200, { discussion }); axiosMock.onAny().reply(200, { discussion });
testAction( return testAction(
actions.replyToDiscussion, actions.replyToDiscussion,
payload, payload,
{ {
...@@ -802,15 +769,14 @@ describe('Actions Notes Store', () => { ...@@ -802,15 +769,14 @@ describe('Actions Notes Store', () => {
{ type: 'startTaskList' }, { type: 'startTaskList' },
{ type: 'updateResolvableDiscussionsCounts' }, { type: 'updateResolvableDiscussionsCounts' },
], ],
done,
); );
}); });
it('adds a reply to a discussion', (done) => { it('adds a reply to a discussion', () => {
const res = {}; const res = {};
axiosMock.onAny().reply(200, res); axiosMock.onAny().reply(200, res);
testAction( return testAction(
actions.replyToDiscussion, actions.replyToDiscussion,
payload, payload,
{ {
...@@ -818,21 +784,19 @@ describe('Actions Notes Store', () => { ...@@ -818,21 +784,19 @@ describe('Actions Notes Store', () => {
}, },
[{ type: mutationTypes.ADD_NEW_REPLY_TO_DISCUSSION, payload: res }], [{ type: mutationTypes.ADD_NEW_REPLY_TO_DISCUSSION, payload: res }],
[], [],
done,
); );
}); });
}); });
describe('removeConvertedDiscussion', () => { describe('removeConvertedDiscussion', () => {
it('commits CONVERT_TO_DISCUSSION with noteId', (done) => { it('commits CONVERT_TO_DISCUSSION with noteId', () => {
const noteId = 'dummy-id'; const noteId = 'dummy-id';
testAction( return testAction(
actions.removeConvertedDiscussion, actions.removeConvertedDiscussion,
noteId, noteId,
{}, {},
[{ type: 'REMOVE_CONVERTED_DISCUSSION', payload: noteId }], [{ type: 'REMOVE_CONVERTED_DISCUSSION', payload: noteId }],
[], [],
done,
); );
}); });
}); });
...@@ -849,8 +813,8 @@ describe('Actions Notes Store', () => { ...@@ -849,8 +813,8 @@ describe('Actions Notes Store', () => {
}; };
}); });
it('when unresolved, dispatches action', (done) => { it('when unresolved, dispatches action', () => {
testAction( return testAction(
actions.resolveDiscussion, actions.resolveDiscussion,
{ discussionId }, { discussionId },
{ ...state, ...getters }, { ...state, ...getters },
...@@ -865,20 +829,18 @@ describe('Actions Notes Store', () => { ...@@ -865,20 +829,18 @@ describe('Actions Notes Store', () => {
}, },
}, },
], ],
done,
); );
}); });
it('when resolved, does nothing', (done) => { it('when resolved, does nothing', () => {
getters.isDiscussionResolved = (id) => id === discussionId; getters.isDiscussionResolved = (id) => id === discussionId;
testAction( return testAction(
actions.resolveDiscussion, actions.resolveDiscussion,
{ discussionId }, { discussionId },
{ ...state, ...getters }, { ...state, ...getters },
[], [],
[], [],
done,
); );
}); });
}); });
...@@ -891,22 +853,17 @@ describe('Actions Notes Store', () => { ...@@ -891,22 +853,17 @@ describe('Actions Notes Store', () => {
const res = { errors: { something: ['went wrong'] } }; const res = { errors: { something: ['went wrong'] } };
const error = { message: 'Unprocessable entity', response: { data: res } }; const error = { message: 'Unprocessable entity', response: { data: res } };
it('throws an error', (done) => { it('throws an error', async () => {
actions await expect(
.saveNote( actions.saveNote(
{ {
commit() {}, commit() {},
dispatch: () => Promise.reject(error), dispatch: () => Promise.reject(error),
}, },
payload, payload,
) ),
.then(() => done.fail('Expected error to be thrown!')) ).rejects.toEqual(error);
.catch((err) => {
expect(err).toBe(error);
expect(createFlash).not.toHaveBeenCalled(); expect(createFlash).not.toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -914,46 +871,35 @@ describe('Actions Notes Store', () => { ...@@ -914,46 +871,35 @@ describe('Actions Notes Store', () => {
const res = { errors: { base: ['something went wrong'] } }; const res = { errors: { base: ['something went wrong'] } };
const error = { message: 'Unprocessable entity', response: { data: res } }; const error = { message: 'Unprocessable entity', response: { data: res } };
it('sets flash alert using errors.base message', (done) => { it('sets flash alert using errors.base message', async () => {
actions const resp = await actions.saveNote(
.saveNote(
{ {
commit() {}, commit() {},
dispatch: () => Promise.reject(error), dispatch: () => Promise.reject(error),
}, },
{ ...payload, flashContainer }, { ...payload, flashContainer },
) );
.then((resp) => {
expect(resp.hasFlash).toBe(true); expect(resp.hasFlash).toBe(true);
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: 'Your comment could not be submitted because something went wrong', message: 'Your comment could not be submitted because something went wrong',
parent: flashContainer, parent: flashContainer,
}); });
})
.catch(() => done.fail('Expected success response!'))
.then(done)
.catch(done.fail);
}); });
}); });
describe('if response contains no errors', () => { describe('if response contains no errors', () => {
const res = { valid: true }; const res = { valid: true };
it('returns the response', (done) => { it('returns the response', async () => {
actions const data = await actions.saveNote(
.saveNote(
{ {
commit() {}, commit() {},
dispatch: () => Promise.resolve(res), dispatch: () => Promise.resolve(res),
}, },
payload, payload,
) );
.then((data) => {
expect(data).toBe(res); expect(data).toBe(res);
expect(createFlash).not.toHaveBeenCalled(); expect(createFlash).not.toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
}); });
}); });
}); });
...@@ -970,19 +916,17 @@ describe('Actions Notes Store', () => { ...@@ -970,19 +916,17 @@ describe('Actions Notes Store', () => {
flashContainer = {}; flashContainer = {};
}); });
const testSubmitSuggestion = (done, expectFn) => { const testSubmitSuggestion = async (expectFn) => {
actions await actions.submitSuggestion(
.submitSuggestion(
{ commit, dispatch }, { commit, dispatch },
{ discussionId, noteId, suggestionId, flashContainer }, { discussionId, noteId, suggestionId, flashContainer },
) );
.then(expectFn)
.then(done) expectFn();
.catch(done.fail);
}; };
it('when service success, commits and resolves discussion', (done) => { it('when service success, commits and resolves discussion', () => {
testSubmitSuggestion(done, () => { testSubmitSuggestion(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, false], [mutationTypes.SET_RESOLVING_DISCUSSION, false],
...@@ -997,12 +941,12 @@ describe('Actions Notes Store', () => { ...@@ -997,12 +941,12 @@ describe('Actions Notes Store', () => {
}); });
}); });
it('when service fails, flashes error message', (done) => { it('when service fails, flashes error message', () => {
const response = { response: { data: { message: TEST_ERROR_MESSAGE } } }; const response = { response: { data: { message: TEST_ERROR_MESSAGE } } };
Api.applySuggestion.mockReturnValue(Promise.reject(response)); Api.applySuggestion.mockReturnValue(Promise.reject(response));
testSubmitSuggestion(done, () => { return testSubmitSuggestion(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, false], [mutationTypes.SET_RESOLVING_DISCUSSION, false],
...@@ -1015,12 +959,12 @@ describe('Actions Notes Store', () => { ...@@ -1015,12 +959,12 @@ describe('Actions Notes Store', () => {
}); });
}); });
it('when service fails, and no error message available, uses default message', (done) => { it('when service fails, and no error message available, uses default message', () => {
const response = { response: 'foo' }; const response = { response: 'foo' };
Api.applySuggestion.mockReturnValue(Promise.reject(response)); Api.applySuggestion.mockReturnValue(Promise.reject(response));
testSubmitSuggestion(done, () => { return testSubmitSuggestion(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, false], [mutationTypes.SET_RESOLVING_DISCUSSION, false],
...@@ -1033,10 +977,10 @@ describe('Actions Notes Store', () => { ...@@ -1033,10 +977,10 @@ describe('Actions Notes Store', () => {
}); });
}); });
it('when resolve discussion fails, fail gracefully', (done) => { it('when resolve discussion fails, fail gracefully', () => {
dispatch.mockReturnValue(Promise.reject()); dispatch.mockReturnValue(Promise.reject());
testSubmitSuggestion(done, () => { return testSubmitSuggestion(() => {
expect(createFlash).not.toHaveBeenCalled(); expect(createFlash).not.toHaveBeenCalled();
}); });
}); });
...@@ -1056,16 +1000,14 @@ describe('Actions Notes Store', () => { ...@@ -1056,16 +1000,14 @@ describe('Actions Notes Store', () => {
flashContainer = {}; flashContainer = {};
}); });
const testSubmitSuggestionBatch = (done, expectFn) => { const testSubmitSuggestionBatch = async (expectFn) => {
actions await actions.submitSuggestionBatch({ commit, dispatch, state }, { flashContainer });
.submitSuggestionBatch({ commit, dispatch, state }, { flashContainer })
.then(expectFn) expectFn();
.then(done)
.catch(done.fail);
}; };
it('when service succeeds, commits, resolves discussions, resets batch and applying batch state', (done) => { it('when service succeeds, commits, resolves discussions, resets batch and applying batch state', () => {
testSubmitSuggestionBatch(done, () => { testSubmitSuggestionBatch(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_APPLYING_BATCH_STATE, true], [mutationTypes.SET_APPLYING_BATCH_STATE, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
...@@ -1085,12 +1027,12 @@ describe('Actions Notes Store', () => { ...@@ -1085,12 +1027,12 @@ describe('Actions Notes Store', () => {
}); });
}); });
it('when service fails, flashes error message, resets applying batch state', (done) => { it('when service fails, flashes error message, resets applying batch state', () => {
const response = { response: { data: { message: TEST_ERROR_MESSAGE } } }; const response = { response: { data: { message: TEST_ERROR_MESSAGE } } };
Api.applySuggestionBatch.mockReturnValue(Promise.reject(response)); Api.applySuggestionBatch.mockReturnValue(Promise.reject(response));
testSubmitSuggestionBatch(done, () => { testSubmitSuggestionBatch(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_APPLYING_BATCH_STATE, true], [mutationTypes.SET_APPLYING_BATCH_STATE, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
...@@ -1106,12 +1048,12 @@ describe('Actions Notes Store', () => { ...@@ -1106,12 +1048,12 @@ describe('Actions Notes Store', () => {
}); });
}); });
it('when service fails, and no error message available, uses default message', (done) => { it('when service fails, and no error message available, uses default message', () => {
const response = { response: 'foo' }; const response = { response: 'foo' };
Api.applySuggestionBatch.mockReturnValue(Promise.reject(response)); Api.applySuggestionBatch.mockReturnValue(Promise.reject(response));
testSubmitSuggestionBatch(done, () => { testSubmitSuggestionBatch(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_APPLYING_BATCH_STATE, true], [mutationTypes.SET_APPLYING_BATCH_STATE, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
...@@ -1128,10 +1070,10 @@ describe('Actions Notes Store', () => { ...@@ -1128,10 +1070,10 @@ describe('Actions Notes Store', () => {
}); });
}); });
it('when resolve discussions fails, fails gracefully, resets batch and applying batch state', (done) => { it('when resolve discussions fails, fails gracefully, resets batch and applying batch state', () => {
dispatch.mockReturnValue(Promise.reject()); dispatch.mockReturnValue(Promise.reject());
testSubmitSuggestionBatch(done, () => { testSubmitSuggestionBatch(() => {
expect(commit.mock.calls).toEqual([ expect(commit.mock.calls).toEqual([
[mutationTypes.SET_APPLYING_BATCH_STATE, true], [mutationTypes.SET_APPLYING_BATCH_STATE, true],
[mutationTypes.SET_RESOLVING_DISCUSSION, true], [mutationTypes.SET_RESOLVING_DISCUSSION, true],
...@@ -1148,14 +1090,13 @@ describe('Actions Notes Store', () => { ...@@ -1148,14 +1090,13 @@ describe('Actions Notes Store', () => {
describe('addSuggestionInfoToBatch', () => { describe('addSuggestionInfoToBatch', () => {
const suggestionInfo = batchSuggestionsInfoMock[0]; const suggestionInfo = batchSuggestionsInfoMock[0];
it("adds a suggestion's info to the current batch", (done) => { it("adds a suggestion's info to the current batch", () => {
testAction( return testAction(
actions.addSuggestionInfoToBatch, actions.addSuggestionInfoToBatch,
suggestionInfo, suggestionInfo,
{ batchSuggestionsInfo: [] }, { batchSuggestionsInfo: [] },
[{ type: 'ADD_SUGGESTION_TO_BATCH', payload: suggestionInfo }], [{ type: 'ADD_SUGGESTION_TO_BATCH', payload: suggestionInfo }],
[], [],
done,
); );
}); });
}); });
...@@ -1163,14 +1104,13 @@ describe('Actions Notes Store', () => { ...@@ -1163,14 +1104,13 @@ describe('Actions Notes Store', () => {
describe('removeSuggestionInfoFromBatch', () => { describe('removeSuggestionInfoFromBatch', () => {
const suggestionInfo = batchSuggestionsInfoMock[0]; const suggestionInfo = batchSuggestionsInfoMock[0];
it("removes a suggestion's info the current batch", (done) => { it("removes a suggestion's info the current batch", () => {
testAction( return testAction(
actions.removeSuggestionInfoFromBatch, actions.removeSuggestionInfoFromBatch,
suggestionInfo.suggestionId, suggestionInfo.suggestionId,
{ batchSuggestionsInfo: [suggestionInfo] }, { batchSuggestionsInfo: [suggestionInfo] },
[{ type: 'REMOVE_SUGGESTION_FROM_BATCH', payload: suggestionInfo.suggestionId }], [{ type: 'REMOVE_SUGGESTION_FROM_BATCH', payload: suggestionInfo.suggestionId }],
[], [],
done,
); );
}); });
}); });
...@@ -1209,8 +1149,8 @@ describe('Actions Notes Store', () => { ...@@ -1209,8 +1149,8 @@ describe('Actions Notes Store', () => {
}); });
describe('setDiscussionSortDirection', () => { describe('setDiscussionSortDirection', () => {
it('calls the correct mutation with the correct args', (done) => { it('calls the correct mutation with the correct args', () => {
testAction( return testAction(
actions.setDiscussionSortDirection, actions.setDiscussionSortDirection,
{ direction: notesConstants.DESC, persist: false }, { direction: notesConstants.DESC, persist: false },
{}, {},
...@@ -1221,20 +1161,18 @@ describe('Actions Notes Store', () => { ...@@ -1221,20 +1161,18 @@ describe('Actions Notes Store', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('setSelectedCommentPosition', () => { describe('setSelectedCommentPosition', () => {
it('calls the correct mutation with the correct args', (done) => { it('calls the correct mutation with the correct args', () => {
testAction( return testAction(
actions.setSelectedCommentPosition, actions.setSelectedCommentPosition,
{}, {},
{}, {},
[{ type: mutationTypes.SET_SELECTED_COMMENT_POSITION, payload: {} }], [{ type: mutationTypes.SET_SELECTED_COMMENT_POSITION, payload: {} }],
[], [],
done,
); );
}); });
}); });
...@@ -1248,9 +1186,9 @@ describe('Actions Notes Store', () => { ...@@ -1248,9 +1186,9 @@ describe('Actions Notes Store', () => {
}; };
describe('if response contains no errors', () => { describe('if response contains no errors', () => {
it('dispatches requestDeleteDescriptionVersion', (done) => { it('dispatches requestDeleteDescriptionVersion', () => {
axiosMock.onDelete(endpoint).replyOnce(200); axiosMock.onDelete(endpoint).replyOnce(200);
testAction( return testAction(
actions.softDeleteDescriptionVersion, actions.softDeleteDescriptionVersion,
payload, payload,
{}, {},
...@@ -1264,15 +1202,15 @@ describe('Actions Notes Store', () => { ...@@ -1264,15 +1202,15 @@ describe('Actions Notes Store', () => {
payload: payload.versionId, payload: payload.versionId,
}, },
], ],
done,
); );
}); });
}); });
describe('if response contains errors', () => { describe('if response contains errors', () => {
const errorMessage = 'Request failed with status code 503'; const errorMessage = 'Request failed with status code 503';
it('dispatches receiveDeleteDescriptionVersionError and throws an error', (done) => { it('dispatches receiveDeleteDescriptionVersionError and throws an error', async () => {
axiosMock.onDelete(endpoint).replyOnce(503); axiosMock.onDelete(endpoint).replyOnce(503);
await expect(
testAction( testAction(
actions.softDeleteDescriptionVersion, actions.softDeleteDescriptionVersion,
payload, payload,
...@@ -1287,12 +1225,10 @@ describe('Actions Notes Store', () => { ...@@ -1287,12 +1225,10 @@ describe('Actions Notes Store', () => {
payload: new Error(errorMessage), payload: new Error(errorMessage),
}, },
], ],
) ),
.then(() => done.fail('Expected error to be thrown')) ).rejects.toEqual(new Error());
.catch(() => {
expect(createFlash).toHaveBeenCalled(); expect(createFlash).toHaveBeenCalled();
done();
});
}); });
}); });
}); });
...@@ -1306,14 +1242,13 @@ describe('Actions Notes Store', () => { ...@@ -1306,14 +1242,13 @@ describe('Actions Notes Store', () => {
}); });
describe('updateAssignees', () => { describe('updateAssignees', () => {
it('update the assignees state', (done) => { it('update the assignees state', () => {
testAction( return testAction(
actions.updateAssignees, actions.updateAssignees,
[userDataMock.id], [userDataMock.id],
{ state: noteableDataMock }, { state: noteableDataMock },
[{ type: mutationTypes.UPDATE_ASSIGNEES, payload: [userDataMock.id] }], [{ type: mutationTypes.UPDATE_ASSIGNEES, payload: [userDataMock.id] }],
[], [],
done,
); );
}); });
}); });
...@@ -1376,28 +1311,26 @@ describe('Actions Notes Store', () => { ...@@ -1376,28 +1311,26 @@ describe('Actions Notes Store', () => {
}); });
describe('updateDiscussionPosition', () => { describe('updateDiscussionPosition', () => {
it('update the assignees state', (done) => { it('update the assignees state', () => {
const updatedPosition = { discussionId: 1, position: { test: true } }; const updatedPosition = { discussionId: 1, position: { test: true } };
testAction( return testAction(
actions.updateDiscussionPosition, actions.updateDiscussionPosition,
updatedPosition, updatedPosition,
{ state: { discussions: [] } }, { state: { discussions: [] } },
[{ type: mutationTypes.UPDATE_DISCUSSION_POSITION, payload: updatedPosition }], [{ type: mutationTypes.UPDATE_DISCUSSION_POSITION, payload: updatedPosition }],
[], [],
done,
); );
}); });
}); });
describe('setFetchingState', () => { describe('setFetchingState', () => {
it('commits SET_NOTES_FETCHING_STATE', (done) => { it('commits SET_NOTES_FETCHING_STATE', () => {
testAction( return testAction(
actions.setFetchingState, actions.setFetchingState,
true, true,
null, null,
[{ type: mutationTypes.SET_NOTES_FETCHING_STATE, payload: true }], [{ type: mutationTypes.SET_NOTES_FETCHING_STATE, payload: true }],
[], [],
done,
); );
}); });
}); });
...@@ -1409,9 +1342,9 @@ describe('Actions Notes Store', () => { ...@@ -1409,9 +1342,9 @@ describe('Actions Notes Store', () => {
window.gon = {}; window.gon = {};
}); });
it('updates the discussions and dispatches `updateResolvableDiscussionsCounts`', (done) => { it('updates the discussions and dispatches `updateResolvableDiscussionsCounts`', () => {
axiosMock.onAny().reply(200, { discussion }); axiosMock.onAny().reply(200, { discussion });
testAction( return testAction(
actions.fetchDiscussions, actions.fetchDiscussions,
{}, {},
null, null,
...@@ -1420,14 +1353,13 @@ describe('Actions Notes Store', () => { ...@@ -1420,14 +1353,13 @@ describe('Actions Notes Store', () => {
{ type: mutationTypes.SET_FETCHING_DISCUSSIONS, payload: false }, { type: mutationTypes.SET_FETCHING_DISCUSSIONS, payload: false },
], ],
[{ type: 'updateResolvableDiscussionsCounts' }], [{ type: 'updateResolvableDiscussionsCounts' }],
done,
); );
}); });
it('dispatches `fetchDiscussionsBatch` action if `paginatedIssueDiscussions` feature flag is enabled', (done) => { it('dispatches `fetchDiscussionsBatch` action if `paginatedIssueDiscussions` feature flag is enabled', () => {
window.gon = { features: { paginatedIssueDiscussions: true } }; window.gon = { features: { paginatedIssueDiscussions: true } };
testAction( return testAction(
actions.fetchDiscussions, actions.fetchDiscussions,
{ path: 'test-path', filter: 'test-filter', persistFilter: 'test-persist-filter' }, { path: 'test-path', filter: 'test-filter', persistFilter: 'test-persist-filter' },
null, null,
...@@ -1444,7 +1376,6 @@ describe('Actions Notes Store', () => { ...@@ -1444,7 +1376,6 @@ describe('Actions Notes Store', () => {
}, },
}, },
], ],
done,
); );
}); });
}); });
...@@ -1458,9 +1389,9 @@ describe('Actions Notes Store', () => { ...@@ -1458,9 +1389,9 @@ describe('Actions Notes Store', () => {
const actionPayload = { config, path: 'test-path', perPage: 20 }; const actionPayload = { config, path: 'test-path', perPage: 20 };
it('updates the discussions and dispatches `updateResolvableDiscussionsCounts if there are no headers', (done) => { it('updates the discussions and dispatches `updateResolvableDiscussionsCounts if there are no headers', () => {
axiosMock.onAny().reply(200, { discussion }, {}); axiosMock.onAny().reply(200, { discussion }, {});
testAction( return testAction(
actions.fetchDiscussionsBatch, actions.fetchDiscussionsBatch,
actionPayload, actionPayload,
null, null,
...@@ -1469,13 +1400,12 @@ describe('Actions Notes Store', () => { ...@@ -1469,13 +1400,12 @@ describe('Actions Notes Store', () => {
{ type: mutationTypes.SET_FETCHING_DISCUSSIONS, payload: false }, { type: mutationTypes.SET_FETCHING_DISCUSSIONS, payload: false },
], ],
[{ type: 'updateResolvableDiscussionsCounts' }], [{ type: 'updateResolvableDiscussionsCounts' }],
done,
); );
}); });
it('dispatches itself if there is `x-next-page-cursor` header', (done) => { it('dispatches itself if there is `x-next-page-cursor` header', () => {
axiosMock.onAny().reply(200, { discussion }, { 'x-next-page-cursor': 1 }); axiosMock.onAny().reply(200, { discussion }, { 'x-next-page-cursor': 1 });
testAction( return testAction(
actions.fetchDiscussionsBatch, actions.fetchDiscussionsBatch,
actionPayload, actionPayload,
null, null,
...@@ -1486,7 +1416,6 @@ describe('Actions Notes Store', () => { ...@@ -1486,7 +1416,6 @@ describe('Actions Notes Store', () => {
payload: { ...actionPayload, perPage: 30, cursor: 1 }, payload: { ...actionPayload, perPage: 30, cursor: 1 },
}, },
], ],
done,
); );
}); });
}); });
......
...@@ -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,58 +65,48 @@ describe('Actions Package details store', () => { ...@@ -77,58 +65,48 @@ 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(Api.projectPackage).toHaveBeenCalledWith(packageEntity.project_id, packageEntity.id);
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: FETCH_PACKAGE_VERSIONS_ERROR, message: FETCH_PACKAGE_VERSIONS_ERROR,
type: 'warning', type: 'warning',
}); });
done();
},
);
}); });
}); });
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();
});
}); });
}); });
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( expect(Api.deleteProjectPackageFile).toHaveBeenCalledWith(
packageEntity.project_id, packageEntity.project_id,
packageEntity.id, packageEntity.id,
...@@ -138,19 +116,15 @@ describe('Actions Package details store', () => { ...@@ -138,19 +116,15 @@ describe('Actions Package details store', () => {
message: DELETE_PACKAGE_FILE_SUCCESS_MESSAGE, message: DELETE_PACKAGE_FILE_SUCCESS_MESSAGE,
type: 'success', type: 'success',
}); });
done();
},
);
}); });
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, { expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy }, params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy },
}); });
done();
},
);
}); });
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, { expect(Api.groupPackages).toHaveBeenCalledWith(2, {
params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy }, params: { page: 1, per_page: 20, sort: sorting.sort, order_by: sorting.orderBy },
}); });
done();
},
);
}); });
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,7 +83,7 @@ describe('Actions Package list store', () => { ...@@ -89,7 +83,7 @@ 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, { expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: { params: {
page: 1, page: 1,
...@@ -99,14 +93,11 @@ describe('Actions Package list store', () => { ...@@ -99,14 +93,11 @@ describe('Actions Package list store', () => {
package_type: packageType, package_type: packageType,
}, },
}); });
done();
},
);
}); });
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,7 +121,7 @@ describe('Actions Package list store', () => { ...@@ -133,7 +121,7 @@ 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, { expect(Api.projectPackages).toHaveBeenCalledWith(1, {
params: { params: {
page: 1, page: 1,
...@@ -143,17 +131,14 @@ describe('Actions Package list store', () => { ...@@ -143,17 +131,14 @@ describe('Actions Package list store', () => {
package_type: 'terraform_module', package_type: 'terraform_module',
}, },
}); });
done();
},
);
}); });
}); });
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