Commit 23e90b6e authored by Natalia Tepluhina's avatar Natalia Tepluhina

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

Remove jest test callbacks from specs (1/3)

See merge request gitlab-org/gitlab!84479
parents f4cc4b5a 58c9a083
...@@ -89,11 +89,9 @@ describe('Badge component', () => { ...@@ -89,11 +89,9 @@ describe('Badge component', () => {
}); });
describe('behavior', () => { describe('behavior', () => {
beforeEach((done) => { beforeEach(() => {
setFixtures('<div id="dummy-element"></div>'); setFixtures('<div id="dummy-element"></div>');
createComponent({ ...dummyProps }, '#dummy-element') return createComponent({ ...dummyProps }, '#dummy-element');
.then(done)
.catch(done.fail);
}); });
it('shows a badge image after loading', () => { it('shows a badge image after loading', () => {
......
...@@ -33,41 +33,38 @@ describe('Badges store actions', () => { ...@@ -33,41 +33,38 @@ describe('Badges store actions', () => {
}); });
describe('requestNewBadge', () => { describe('requestNewBadge', () => {
it('commits REQUEST_NEW_BADGE', (done) => { it('commits REQUEST_NEW_BADGE', () => {
testAction( return testAction(
actions.requestNewBadge, actions.requestNewBadge,
null, null,
state, state,
[{ type: mutationTypes.REQUEST_NEW_BADGE }], [{ type: mutationTypes.REQUEST_NEW_BADGE }],
[], [],
done,
); );
}); });
}); });
describe('receiveNewBadge', () => { describe('receiveNewBadge', () => {
it('commits RECEIVE_NEW_BADGE', (done) => { it('commits RECEIVE_NEW_BADGE', () => {
const newBadge = createDummyBadge(); const newBadge = createDummyBadge();
testAction( return testAction(
actions.receiveNewBadge, actions.receiveNewBadge,
newBadge, newBadge,
state, state,
[{ type: mutationTypes.RECEIVE_NEW_BADGE, payload: newBadge }], [{ type: mutationTypes.RECEIVE_NEW_BADGE, payload: newBadge }],
[], [],
done,
); );
}); });
}); });
describe('receiveNewBadgeError', () => { describe('receiveNewBadgeError', () => {
it('commits RECEIVE_NEW_BADGE_ERROR', (done) => { it('commits RECEIVE_NEW_BADGE_ERROR', () => {
testAction( return testAction(
actions.receiveNewBadgeError, actions.receiveNewBadgeError,
null, null,
state, state,
[{ type: mutationTypes.RECEIVE_NEW_BADGE_ERROR }], [{ type: mutationTypes.RECEIVE_NEW_BADGE_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -87,7 +84,7 @@ describe('Badges store actions', () => { ...@@ -87,7 +84,7 @@ describe('Badges store actions', () => {
}; };
}); });
it('dispatches requestNewBadge and receiveNewBadge for successful response', (done) => { it('dispatches requestNewBadge and receiveNewBadge for successful response', async () => {
const dummyResponse = createDummyBadgeResponse(); const dummyResponse = createDummyBadgeResponse();
endpointMock.replyOnce((req) => { endpointMock.replyOnce((req) => {
...@@ -105,16 +102,12 @@ describe('Badges store actions', () => { ...@@ -105,16 +102,12 @@ describe('Badges store actions', () => {
}); });
const dummyBadge = transformBackendBadge(dummyResponse); const dummyBadge = transformBackendBadge(dummyResponse);
actions
.addBadge({ state, dispatch }) await actions.addBadge({ state, dispatch });
.then(() => {
expect(dispatch.mock.calls).toEqual([['receiveNewBadge', dummyBadge]]); expect(dispatch.mock.calls).toEqual([['receiveNewBadge', dummyBadge]]);
})
.then(done)
.catch(done.fail);
}); });
it('dispatches requestNewBadge and receiveNewBadgeError for error response', (done) => { it('dispatches requestNewBadge and receiveNewBadgeError for error response', async () => {
endpointMock.replyOnce((req) => { endpointMock.replyOnce((req) => {
expect(req.data).toBe( expect(req.data).toBe(
JSON.stringify({ JSON.stringify({
...@@ -129,52 +122,43 @@ describe('Badges store actions', () => { ...@@ -129,52 +122,43 @@ describe('Badges store actions', () => {
return [500, '']; return [500, ''];
}); });
actions await expect(actions.addBadge({ state, dispatch })).rejects.toThrow();
.addBadge({ state, dispatch })
.then(() => done.fail('Expected Ajax call to fail!'))
.catch(() => {
expect(dispatch.mock.calls).toEqual([['receiveNewBadgeError']]); expect(dispatch.mock.calls).toEqual([['receiveNewBadgeError']]);
})
.then(done)
.catch(done.fail);
}); });
}); });
describe('requestDeleteBadge', () => { describe('requestDeleteBadge', () => {
it('commits REQUEST_DELETE_BADGE', (done) => { it('commits REQUEST_DELETE_BADGE', () => {
testAction( return testAction(
actions.requestDeleteBadge, actions.requestDeleteBadge,
badgeId, badgeId,
state, state,
[{ type: mutationTypes.REQUEST_DELETE_BADGE, payload: badgeId }], [{ type: mutationTypes.REQUEST_DELETE_BADGE, payload: badgeId }],
[], [],
done,
); );
}); });
}); });
describe('receiveDeleteBadge', () => { describe('receiveDeleteBadge', () => {
it('commits RECEIVE_DELETE_BADGE', (done) => { it('commits RECEIVE_DELETE_BADGE', () => {
testAction( return testAction(
actions.receiveDeleteBadge, actions.receiveDeleteBadge,
badgeId, badgeId,
state, state,
[{ type: mutationTypes.RECEIVE_DELETE_BADGE, payload: badgeId }], [{ type: mutationTypes.RECEIVE_DELETE_BADGE, payload: badgeId }],
[], [],
done,
); );
}); });
}); });
describe('receiveDeleteBadgeError', () => { describe('receiveDeleteBadgeError', () => {
it('commits RECEIVE_DELETE_BADGE_ERROR', (done) => { it('commits RECEIVE_DELETE_BADGE_ERROR', () => {
testAction( return testAction(
actions.receiveDeleteBadgeError, actions.receiveDeleteBadgeError,
badgeId, badgeId,
state, state,
[{ type: mutationTypes.RECEIVE_DELETE_BADGE_ERROR, payload: badgeId }], [{ type: mutationTypes.RECEIVE_DELETE_BADGE_ERROR, payload: badgeId }],
[], [],
done,
); );
}); });
}); });
...@@ -188,91 +172,76 @@ describe('Badges store actions', () => { ...@@ -188,91 +172,76 @@ describe('Badges store actions', () => {
dispatch = jest.fn(); dispatch = jest.fn();
}); });
it('dispatches requestDeleteBadge and receiveDeleteBadge for successful response', (done) => { it('dispatches requestDeleteBadge and receiveDeleteBadge for successful response', async () => {
endpointMock.replyOnce(() => { endpointMock.replyOnce(() => {
expect(dispatch.mock.calls).toEqual([['requestDeleteBadge', badgeId]]); expect(dispatch.mock.calls).toEqual([['requestDeleteBadge', badgeId]]);
dispatch.mockClear(); dispatch.mockClear();
return [200, '']; return [200, ''];
}); });
actions await actions.deleteBadge({ state, dispatch }, { id: badgeId });
.deleteBadge({ state, dispatch }, { id: badgeId })
.then(() => {
expect(dispatch.mock.calls).toEqual([['receiveDeleteBadge', badgeId]]); expect(dispatch.mock.calls).toEqual([['receiveDeleteBadge', badgeId]]);
})
.then(done)
.catch(done.fail);
}); });
it('dispatches requestDeleteBadge and receiveDeleteBadgeError for error response', (done) => { it('dispatches requestDeleteBadge and receiveDeleteBadgeError for error response', async () => {
endpointMock.replyOnce(() => { endpointMock.replyOnce(() => {
expect(dispatch.mock.calls).toEqual([['requestDeleteBadge', badgeId]]); expect(dispatch.mock.calls).toEqual([['requestDeleteBadge', badgeId]]);
dispatch.mockClear(); dispatch.mockClear();
return [500, '']; return [500, ''];
}); });
actions await expect(actions.deleteBadge({ state, dispatch }, { id: badgeId })).rejects.toThrow();
.deleteBadge({ state, dispatch }, { id: badgeId })
.then(() => done.fail('Expected Ajax call to fail!'))
.catch(() => {
expect(dispatch.mock.calls).toEqual([['receiveDeleteBadgeError', badgeId]]); expect(dispatch.mock.calls).toEqual([['receiveDeleteBadgeError', badgeId]]);
})
.then(done)
.catch(done.fail);
}); });
}); });
describe('editBadge', () => { describe('editBadge', () => {
it('commits START_EDITING', (done) => { it('commits START_EDITING', () => {
const dummyBadge = createDummyBadge(); const dummyBadge = createDummyBadge();
testAction( return testAction(
actions.editBadge, actions.editBadge,
dummyBadge, dummyBadge,
state, state,
[{ type: mutationTypes.START_EDITING, payload: dummyBadge }], [{ type: mutationTypes.START_EDITING, payload: dummyBadge }],
[], [],
done,
); );
}); });
}); });
describe('requestLoadBadges', () => { describe('requestLoadBadges', () => {
it('commits REQUEST_LOAD_BADGES', (done) => { it('commits REQUEST_LOAD_BADGES', () => {
const dummyData = 'this is not real data'; const dummyData = 'this is not real data';
testAction( return testAction(
actions.requestLoadBadges, actions.requestLoadBadges,
dummyData, dummyData,
state, state,
[{ type: mutationTypes.REQUEST_LOAD_BADGES, payload: dummyData }], [{ type: mutationTypes.REQUEST_LOAD_BADGES, payload: dummyData }],
[], [],
done,
); );
}); });
}); });
describe('receiveLoadBadges', () => { describe('receiveLoadBadges', () => {
it('commits RECEIVE_LOAD_BADGES', (done) => { it('commits RECEIVE_LOAD_BADGES', () => {
const badges = dummyBadges; const badges = dummyBadges;
testAction( return testAction(
actions.receiveLoadBadges, actions.receiveLoadBadges,
badges, badges,
state, state,
[{ type: mutationTypes.RECEIVE_LOAD_BADGES, payload: badges }], [{ type: mutationTypes.RECEIVE_LOAD_BADGES, payload: badges }],
[], [],
done,
); );
}); });
}); });
describe('receiveLoadBadgesError', () => { describe('receiveLoadBadgesError', () => {
it('commits RECEIVE_LOAD_BADGES_ERROR', (done) => { it('commits RECEIVE_LOAD_BADGES_ERROR', () => {
testAction( return testAction(
actions.receiveLoadBadgesError, actions.receiveLoadBadgesError,
null, null,
state, state,
[{ type: mutationTypes.RECEIVE_LOAD_BADGES_ERROR }], [{ type: mutationTypes.RECEIVE_LOAD_BADGES_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -286,7 +255,7 @@ describe('Badges store actions', () => { ...@@ -286,7 +255,7 @@ describe('Badges store actions', () => {
dispatch = jest.fn(); dispatch = jest.fn();
}); });
it('dispatches requestLoadBadges and receiveLoadBadges for successful response', (done) => { it('dispatches requestLoadBadges and receiveLoadBadges for successful response', async () => {
const dummyData = 'this is just some data'; const dummyData = 'this is just some data';
const dummyReponse = [ const dummyReponse = [
createDummyBadgeResponse(), createDummyBadgeResponse(),
...@@ -299,18 +268,13 @@ describe('Badges store actions', () => { ...@@ -299,18 +268,13 @@ describe('Badges store actions', () => {
return [200, dummyReponse]; return [200, dummyReponse];
}); });
actions await actions.loadBadges({ state, dispatch }, dummyData);
.loadBadges({ state, dispatch }, dummyData)
.then(() => {
const badges = dummyReponse.map(transformBackendBadge); const badges = dummyReponse.map(transformBackendBadge);
expect(dispatch.mock.calls).toEqual([['receiveLoadBadges', badges]]); expect(dispatch.mock.calls).toEqual([['receiveLoadBadges', badges]]);
})
.then(done)
.catch(done.fail);
}); });
it('dispatches requestLoadBadges and receiveLoadBadgesError for error response', (done) => { it('dispatches requestLoadBadges and receiveLoadBadgesError for error response', async () => {
const dummyData = 'this is just some data'; const dummyData = 'this is just some data';
endpointMock.replyOnce(() => { endpointMock.replyOnce(() => {
expect(dispatch.mock.calls).toEqual([['requestLoadBadges', dummyData]]); expect(dispatch.mock.calls).toEqual([['requestLoadBadges', dummyData]]);
...@@ -318,53 +282,44 @@ describe('Badges store actions', () => { ...@@ -318,53 +282,44 @@ describe('Badges store actions', () => {
return [500, '']; return [500, ''];
}); });
actions await expect(actions.loadBadges({ state, dispatch }, dummyData)).rejects.toThrow();
.loadBadges({ state, dispatch }, dummyData)
.then(() => done.fail('Expected Ajax call to fail!'))
.catch(() => {
expect(dispatch.mock.calls).toEqual([['receiveLoadBadgesError']]); expect(dispatch.mock.calls).toEqual([['receiveLoadBadgesError']]);
})
.then(done)
.catch(done.fail);
}); });
}); });
describe('requestRenderedBadge', () => { describe('requestRenderedBadge', () => {
it('commits REQUEST_RENDERED_BADGE', (done) => { it('commits REQUEST_RENDERED_BADGE', () => {
testAction( return testAction(
actions.requestRenderedBadge, actions.requestRenderedBadge,
null, null,
state, state,
[{ type: mutationTypes.REQUEST_RENDERED_BADGE }], [{ type: mutationTypes.REQUEST_RENDERED_BADGE }],
[], [],
done,
); );
}); });
}); });
describe('receiveRenderedBadge', () => { describe('receiveRenderedBadge', () => {
it('commits RECEIVE_RENDERED_BADGE', (done) => { it('commits RECEIVE_RENDERED_BADGE', () => {
const dummyBadge = createDummyBadge(); const dummyBadge = createDummyBadge();
testAction( return testAction(
actions.receiveRenderedBadge, actions.receiveRenderedBadge,
dummyBadge, dummyBadge,
state, state,
[{ type: mutationTypes.RECEIVE_RENDERED_BADGE, payload: dummyBadge }], [{ type: mutationTypes.RECEIVE_RENDERED_BADGE, payload: dummyBadge }],
[], [],
done,
); );
}); });
}); });
describe('receiveRenderedBadgeError', () => { describe('receiveRenderedBadgeError', () => {
it('commits RECEIVE_RENDERED_BADGE_ERROR', (done) => { it('commits RECEIVE_RENDERED_BADGE_ERROR', () => {
testAction( return testAction(
actions.receiveRenderedBadgeError, actions.receiveRenderedBadgeError,
null, null,
state, state,
[{ type: mutationTypes.RECEIVE_RENDERED_BADGE_ERROR }], [{ type: mutationTypes.RECEIVE_RENDERED_BADGE_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -388,42 +343,30 @@ describe('Badges store actions', () => { ...@@ -388,42 +343,30 @@ describe('Badges store actions', () => {
dispatch = jest.fn(); dispatch = jest.fn();
}); });
it('returns immediately if imageUrl is empty', (done) => { it('returns immediately if imageUrl is empty', async () => {
jest.spyOn(axios, 'get').mockImplementation(() => {}); jest.spyOn(axios, 'get').mockImplementation(() => {});
badgeInForm.imageUrl = ''; badgeInForm.imageUrl = '';
actions await actions.renderBadge({ state, dispatch });
.renderBadge({ state, dispatch })
.then(() => {
expect(axios.get).not.toHaveBeenCalled(); expect(axios.get).not.toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
}); });
it('returns immediately if linkUrl is empty', (done) => { it('returns immediately if linkUrl is empty', async () => {
jest.spyOn(axios, 'get').mockImplementation(() => {}); jest.spyOn(axios, 'get').mockImplementation(() => {});
badgeInForm.linkUrl = ''; badgeInForm.linkUrl = '';
actions await actions.renderBadge({ state, dispatch });
.renderBadge({ state, dispatch })
.then(() => {
expect(axios.get).not.toHaveBeenCalled(); expect(axios.get).not.toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
}); });
it('escapes user input', (done) => { it('escapes user input', async () => {
jest jest
.spyOn(axios, 'get') .spyOn(axios, 'get')
.mockImplementation(() => Promise.resolve({ data: createDummyBadgeResponse() })); .mockImplementation(() => Promise.resolve({ data: createDummyBadgeResponse() }));
badgeInForm.imageUrl = '&make-sandwich=true'; badgeInForm.imageUrl = '&make-sandwich=true';
badgeInForm.linkUrl = '<script>I am dangerous!</script>'; badgeInForm.linkUrl = '<script>I am dangerous!</script>';
actions await actions.renderBadge({ state, dispatch });
.renderBadge({ state, dispatch })
.then(() => {
expect(axios.get.mock.calls.length).toBe(1); expect(axios.get.mock.calls.length).toBe(1);
const url = axios.get.mock.calls[0][0]; const url = axios.get.mock.calls[0][0];
...@@ -432,12 +375,9 @@ describe('Badges store actions', () => { ...@@ -432,12 +375,9 @@ describe('Badges store actions', () => {
new RegExp('\\?link_url=%3Cscript%3EI%20am%20dangerous!%3C%2Fscript%3E&'), new RegExp('\\?link_url=%3Cscript%3EI%20am%20dangerous!%3C%2Fscript%3E&'),
); );
expect(url).toMatch(new RegExp('&image_url=%26make-sandwich%3Dtrue$')); expect(url).toMatch(new RegExp('&image_url=%26make-sandwich%3Dtrue$'));
})
.then(done)
.catch(done.fail);
}); });
it('dispatches requestRenderedBadge and receiveRenderedBadge for successful response', (done) => { it('dispatches requestRenderedBadge and receiveRenderedBadge for successful response', async () => {
const dummyReponse = createDummyBadgeResponse(); const dummyReponse = createDummyBadgeResponse();
endpointMock.replyOnce(() => { endpointMock.replyOnce(() => {
expect(dispatch.mock.calls).toEqual([['requestRenderedBadge']]); expect(dispatch.mock.calls).toEqual([['requestRenderedBadge']]);
...@@ -445,71 +385,57 @@ describe('Badges store actions', () => { ...@@ -445,71 +385,57 @@ describe('Badges store actions', () => {
return [200, dummyReponse]; return [200, dummyReponse];
}); });
actions await actions.renderBadge({ state, dispatch });
.renderBadge({ state, dispatch })
.then(() => {
const renderedBadge = transformBackendBadge(dummyReponse); const renderedBadge = transformBackendBadge(dummyReponse);
expect(dispatch.mock.calls).toEqual([['receiveRenderedBadge', renderedBadge]]); expect(dispatch.mock.calls).toEqual([['receiveRenderedBadge', renderedBadge]]);
})
.then(done)
.catch(done.fail);
}); });
it('dispatches requestRenderedBadge and receiveRenderedBadgeError for error response', (done) => { it('dispatches requestRenderedBadge and receiveRenderedBadgeError for error response', async () => {
endpointMock.replyOnce(() => { endpointMock.replyOnce(() => {
expect(dispatch.mock.calls).toEqual([['requestRenderedBadge']]); expect(dispatch.mock.calls).toEqual([['requestRenderedBadge']]);
dispatch.mockClear(); dispatch.mockClear();
return [500, '']; return [500, ''];
}); });
actions await expect(actions.renderBadge({ state, dispatch })).rejects.toThrow();
.renderBadge({ state, dispatch })
.then(() => done.fail('Expected Ajax call to fail!'))
.catch(() => {
expect(dispatch.mock.calls).toEqual([['receiveRenderedBadgeError']]); expect(dispatch.mock.calls).toEqual([['receiveRenderedBadgeError']]);
})
.then(done)
.catch(done.fail);
}); });
}); });
describe('requestUpdatedBadge', () => { describe('requestUpdatedBadge', () => {
it('commits REQUEST_UPDATED_BADGE', (done) => { it('commits REQUEST_UPDATED_BADGE', () => {
testAction( return testAction(
actions.requestUpdatedBadge, actions.requestUpdatedBadge,
null, null,
state, state,
[{ type: mutationTypes.REQUEST_UPDATED_BADGE }], [{ type: mutationTypes.REQUEST_UPDATED_BADGE }],
[], [],
done,
); );
}); });
}); });
describe('receiveUpdatedBadge', () => { describe('receiveUpdatedBadge', () => {
it('commits RECEIVE_UPDATED_BADGE', (done) => { it('commits RECEIVE_UPDATED_BADGE', () => {
const updatedBadge = createDummyBadge(); const updatedBadge = createDummyBadge();
testAction( return testAction(
actions.receiveUpdatedBadge, actions.receiveUpdatedBadge,
updatedBadge, updatedBadge,
state, state,
[{ type: mutationTypes.RECEIVE_UPDATED_BADGE, payload: updatedBadge }], [{ type: mutationTypes.RECEIVE_UPDATED_BADGE, payload: updatedBadge }],
[], [],
done,
); );
}); });
}); });
describe('receiveUpdatedBadgeError', () => { describe('receiveUpdatedBadgeError', () => {
it('commits RECEIVE_UPDATED_BADGE_ERROR', (done) => { it('commits RECEIVE_UPDATED_BADGE_ERROR', () => {
testAction( return testAction(
actions.receiveUpdatedBadgeError, actions.receiveUpdatedBadgeError,
null, null,
state, state,
[{ type: mutationTypes.RECEIVE_UPDATED_BADGE_ERROR }], [{ type: mutationTypes.RECEIVE_UPDATED_BADGE_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -529,7 +455,7 @@ describe('Badges store actions', () => { ...@@ -529,7 +455,7 @@ describe('Badges store actions', () => {
dispatch = jest.fn(); dispatch = jest.fn();
}); });
it('dispatches requestUpdatedBadge and receiveUpdatedBadge for successful response', (done) => { it('dispatches requestUpdatedBadge and receiveUpdatedBadge for successful response', async () => {
const dummyResponse = createDummyBadgeResponse(); const dummyResponse = createDummyBadgeResponse();
endpointMock.replyOnce((req) => { endpointMock.replyOnce((req) => {
...@@ -547,16 +473,11 @@ describe('Badges store actions', () => { ...@@ -547,16 +473,11 @@ describe('Badges store actions', () => {
}); });
const updatedBadge = transformBackendBadge(dummyResponse); const updatedBadge = transformBackendBadge(dummyResponse);
actions await actions.saveBadge({ state, dispatch });
.saveBadge({ state, dispatch })
.then(() => {
expect(dispatch.mock.calls).toEqual([['receiveUpdatedBadge', updatedBadge]]); expect(dispatch.mock.calls).toEqual([['receiveUpdatedBadge', updatedBadge]]);
})
.then(done)
.catch(done.fail);
}); });
it('dispatches requestUpdatedBadge and receiveUpdatedBadgeError for error response', (done) => { it('dispatches requestUpdatedBadge and receiveUpdatedBadgeError for error response', async () => {
endpointMock.replyOnce((req) => { endpointMock.replyOnce((req) => {
expect(req.data).toBe( expect(req.data).toBe(
JSON.stringify({ JSON.stringify({
...@@ -571,53 +492,44 @@ describe('Badges store actions', () => { ...@@ -571,53 +492,44 @@ describe('Badges store actions', () => {
return [500, '']; return [500, ''];
}); });
actions await expect(actions.saveBadge({ state, dispatch })).rejects.toThrow();
.saveBadge({ state, dispatch })
.then(() => done.fail('Expected Ajax call to fail!'))
.catch(() => {
expect(dispatch.mock.calls).toEqual([['receiveUpdatedBadgeError']]); expect(dispatch.mock.calls).toEqual([['receiveUpdatedBadgeError']]);
})
.then(done)
.catch(done.fail);
}); });
}); });
describe('stopEditing', () => { describe('stopEditing', () => {
it('commits STOP_EDITING', (done) => { it('commits STOP_EDITING', () => {
testAction( return testAction(
actions.stopEditing, actions.stopEditing,
null, null,
state, state,
[{ type: mutationTypes.STOP_EDITING }], [{ type: mutationTypes.STOP_EDITING }],
[], [],
done,
); );
}); });
}); });
describe('updateBadgeInForm', () => { describe('updateBadgeInForm', () => {
it('commits UPDATE_BADGE_IN_FORM', (done) => { it('commits UPDATE_BADGE_IN_FORM', () => {
const dummyBadge = createDummyBadge(); const dummyBadge = createDummyBadge();
testAction( return testAction(
actions.updateBadgeInForm, actions.updateBadgeInForm,
dummyBadge, dummyBadge,
state, state,
[{ type: mutationTypes.UPDATE_BADGE_IN_FORM, payload: dummyBadge }], [{ type: mutationTypes.UPDATE_BADGE_IN_FORM, payload: dummyBadge }],
[], [],
done,
); );
}); });
describe('updateBadgeInModal', () => { describe('updateBadgeInModal', () => {
it('commits UPDATE_BADGE_IN_MODAL', (done) => { it('commits UPDATE_BADGE_IN_MODAL', () => {
const dummyBadge = createDummyBadge(); const dummyBadge = createDummyBadge();
testAction( return testAction(
actions.updateBadgeInModal, actions.updateBadgeInModal,
dummyBadge, dummyBadge,
state, state,
[{ type: mutationTypes.UPDATE_BADGE_IN_MODAL, payload: dummyBadge }], [{ type: mutationTypes.UPDATE_BADGE_IN_MODAL, payload: dummyBadge }],
[], [],
done,
); );
}); });
}); });
......
...@@ -29,53 +29,56 @@ describe('Batch comments store actions', () => { ...@@ -29,53 +29,56 @@ describe('Batch comments store actions', () => {
}); });
describe('addDraftToDiscussion', () => { describe('addDraftToDiscussion', () => {
it('commits ADD_NEW_DRAFT if no errors returned', (done) => { it('commits ADD_NEW_DRAFT if no errors returned', () => {
res = { id: 1 }; res = { id: 1 };
mock.onAny().reply(200, res); mock.onAny().reply(200, res);
testAction( return testAction(
actions.addDraftToDiscussion, actions.addDraftToDiscussion,
{ endpoint: TEST_HOST, data: 'test' }, { endpoint: TEST_HOST, data: 'test' },
null, null,
[{ type: 'ADD_NEW_DRAFT', payload: res }], [{ type: 'ADD_NEW_DRAFT', payload: res }],
[], [],
done,
); );
}); });
it('does not commit ADD_NEW_DRAFT if errors returned', (done) => { it('does not commit ADD_NEW_DRAFT if errors returned', () => {
mock.onAny().reply(500); mock.onAny().reply(500);
testAction( return testAction(
actions.addDraftToDiscussion, actions.addDraftToDiscussion,
{ endpoint: TEST_HOST, data: 'test' }, { endpoint: TEST_HOST, data: 'test' },
null, null,
[], [],
[], [],
done,
); );
}); });
}); });
describe('createNewDraft', () => { describe('createNewDraft', () => {
it('commits ADD_NEW_DRAFT if no errors returned', (done) => { it('commits ADD_NEW_DRAFT if no errors returned', () => {
res = { id: 1 }; res = { id: 1 };
mock.onAny().reply(200, res); mock.onAny().reply(200, res);
testAction( return testAction(
actions.createNewDraft, actions.createNewDraft,
{ endpoint: TEST_HOST, data: 'test' }, { endpoint: TEST_HOST, data: 'test' },
null, null,
[{ type: 'ADD_NEW_DRAFT', payload: res }], [{ type: 'ADD_NEW_DRAFT', payload: res }],
[], [],
done,
); );
}); });
it('does not commit ADD_NEW_DRAFT if errors returned', (done) => { it('does not commit ADD_NEW_DRAFT if errors returned', () => {
mock.onAny().reply(500); mock.onAny().reply(500);
testAction(actions.createNewDraft, { endpoint: TEST_HOST, data: 'test' }, null, [], [], done); return testAction(
actions.createNewDraft,
{ endpoint: TEST_HOST, data: 'test' },
null,
[],
[],
);
}); });
}); });
...@@ -90,7 +93,7 @@ describe('Batch comments store actions', () => { ...@@ -90,7 +93,7 @@ describe('Batch comments store actions', () => {
}; };
}); });
it('commits DELETE_DRAFT if no errors returned', (done) => { it('commits DELETE_DRAFT if no errors returned', () => {
const commit = jest.fn(); const commit = jest.fn();
const context = { const context = {
getters, getters,
...@@ -99,16 +102,12 @@ describe('Batch comments store actions', () => { ...@@ -99,16 +102,12 @@ describe('Batch comments store actions', () => {
res = { id: 1 }; res = { id: 1 };
mock.onAny().reply(200); mock.onAny().reply(200);
actions return actions.deleteDraft(context, { id: 1 }).then(() => {
.deleteDraft(context, { id: 1 })
.then(() => {
expect(commit).toHaveBeenCalledWith('DELETE_DRAFT', 1); expect(commit).toHaveBeenCalledWith('DELETE_DRAFT', 1);
}) });
.then(done)
.catch(done.fail);
}); });
it('does not commit DELETE_DRAFT if errors returned', (done) => { it('does not commit DELETE_DRAFT if errors returned', () => {
const commit = jest.fn(); const commit = jest.fn();
const context = { const context = {
getters, getters,
...@@ -116,13 +115,9 @@ describe('Batch comments store actions', () => { ...@@ -116,13 +115,9 @@ describe('Batch comments store actions', () => {
}; };
mock.onAny().reply(500); mock.onAny().reply(500);
actions return actions.deleteDraft(context, { id: 1 }).then(() => {
.deleteDraft(context, { id: 1 })
.then(() => {
expect(commit).not.toHaveBeenCalledWith('DELETE_DRAFT', 1); expect(commit).not.toHaveBeenCalledWith('DELETE_DRAFT', 1);
}) });
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -137,7 +132,7 @@ describe('Batch comments store actions', () => { ...@@ -137,7 +132,7 @@ describe('Batch comments store actions', () => {
}; };
}); });
it('commits SET_BATCH_COMMENTS_DRAFTS with returned data', (done) => { it('commits SET_BATCH_COMMENTS_DRAFTS with returned data', () => {
const commit = jest.fn(); const commit = jest.fn();
const dispatch = jest.fn(); const dispatch = jest.fn();
const context = { const context = {
...@@ -151,14 +146,10 @@ describe('Batch comments store actions', () => { ...@@ -151,14 +146,10 @@ describe('Batch comments store actions', () => {
res = { id: 1 }; res = { id: 1 };
mock.onAny().reply(200, res); mock.onAny().reply(200, res);
actions return actions.fetchDrafts(context).then(() => {
.fetchDrafts(context)
.then(() => {
expect(commit).toHaveBeenCalledWith('SET_BATCH_COMMENTS_DRAFTS', { id: 1 }); expect(commit).toHaveBeenCalledWith('SET_BATCH_COMMENTS_DRAFTS', { id: 1 });
expect(dispatch).toHaveBeenCalledWith('convertToDiscussion', '1', { root: true }); expect(dispatch).toHaveBeenCalledWith('convertToDiscussion', '1', { root: true });
}) });
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -177,32 +168,24 @@ describe('Batch comments store actions', () => { ...@@ -177,32 +168,24 @@ describe('Batch comments store actions', () => {
rootGetters = { discussionsStructuredByLineCode: 'discussions' }; rootGetters = { discussionsStructuredByLineCode: 'discussions' };
}); });
it('dispatches actions & commits', (done) => { it('dispatches actions & commits', () => {
mock.onAny().reply(200); mock.onAny().reply(200);
actions return actions.publishReview({ dispatch, commit, getters, rootGetters }).then(() => {
.publishReview({ dispatch, commit, getters, rootGetters })
.then(() => {
expect(commit.mock.calls[0]).toEqual(['REQUEST_PUBLISH_REVIEW']); expect(commit.mock.calls[0]).toEqual(['REQUEST_PUBLISH_REVIEW']);
expect(commit.mock.calls[1]).toEqual(['RECEIVE_PUBLISH_REVIEW_SUCCESS']); expect(commit.mock.calls[1]).toEqual(['RECEIVE_PUBLISH_REVIEW_SUCCESS']);
expect(dispatch.mock.calls[0]).toEqual(['updateDiscussionsAfterPublish']); expect(dispatch.mock.calls[0]).toEqual(['updateDiscussionsAfterPublish']);
}) });
.then(done)
.catch(done.fail);
}); });
it('dispatches error commits', (done) => { it('dispatches error commits', () => {
mock.onAny().reply(500); mock.onAny().reply(500);
actions return actions.publishReview({ dispatch, commit, getters, rootGetters }).then(() => {
.publishReview({ dispatch, commit, getters, rootGetters })
.then(() => {
expect(commit.mock.calls[0]).toEqual(['REQUEST_PUBLISH_REVIEW']); expect(commit.mock.calls[0]).toEqual(['REQUEST_PUBLISH_REVIEW']);
expect(commit.mock.calls[1]).toEqual(['RECEIVE_PUBLISH_REVIEW_ERROR']); expect(commit.mock.calls[1]).toEqual(['RECEIVE_PUBLISH_REVIEW_ERROR']);
}) });
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -262,7 +245,7 @@ describe('Batch comments store actions', () => { ...@@ -262,7 +245,7 @@ describe('Batch comments store actions', () => {
}); });
describe('expandAllDiscussions', () => { describe('expandAllDiscussions', () => {
it('dispatches expandDiscussion for all drafts', (done) => { it('dispatches expandDiscussion for all drafts', () => {
const state = { const state = {
drafts: [ drafts: [
{ {
...@@ -271,7 +254,7 @@ describe('Batch comments store actions', () => { ...@@ -271,7 +254,7 @@ describe('Batch comments store actions', () => {
], ],
}; };
testAction( return testAction(
actions.expandAllDiscussions, actions.expandAllDiscussions,
null, null,
state, state,
...@@ -282,7 +265,6 @@ describe('Batch comments store actions', () => { ...@@ -282,7 +265,6 @@ describe('Batch comments store actions', () => {
payload: { discussionId: '1' }, payload: { discussionId: '1' },
}, },
], ],
done,
); );
}); });
}); });
......
...@@ -166,31 +166,29 @@ describe('setFilters', () => { ...@@ -166,31 +166,29 @@ describe('setFilters', () => {
}); });
describe('performSearch', () => { describe('performSearch', () => {
it('should dispatch setFilters, fetchLists and resetIssues action', (done) => { it('should dispatch setFilters, fetchLists and resetIssues action', () => {
testAction( return testAction(
actions.performSearch, actions.performSearch,
{}, {},
{}, {},
[], [],
[{ type: 'setFilters', payload: {} }, { type: 'fetchLists' }, { type: 'resetIssues' }], [{ type: 'setFilters', payload: {} }, { type: 'fetchLists' }, { type: 'resetIssues' }],
done,
); );
}); });
}); });
describe('setActiveId', () => { describe('setActiveId', () => {
it('should commit mutation SET_ACTIVE_ID', (done) => { it('should commit mutation SET_ACTIVE_ID', () => {
const state = { const state = {
activeId: inactiveId, activeId: inactiveId,
}; };
testAction( return testAction(
actions.setActiveId, actions.setActiveId,
{ id: 1, sidebarType: 'something' }, { id: 1, sidebarType: 'something' },
state, state,
[{ type: types.SET_ACTIVE_ID, payload: { id: 1, sidebarType: 'something' } }], [{ type: types.SET_ACTIVE_ID, payload: { id: 1, sidebarType: 'something' } }],
[], [],
done,
); );
}); });
}); });
...@@ -219,10 +217,10 @@ describe('fetchLists', () => { ...@@ -219,10 +217,10 @@ describe('fetchLists', () => {
const formattedLists = formatBoardLists(queryResponse.data.group.board.lists); const formattedLists = formatBoardLists(queryResponse.data.group.board.lists);
it('should commit mutations RECEIVE_BOARD_LISTS_SUCCESS on success', (done) => { it('should commit mutations RECEIVE_BOARD_LISTS_SUCCESS on success', () => {
jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse); jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse);
testAction( return testAction(
actions.fetchLists, actions.fetchLists,
{}, {},
state, state,
...@@ -233,14 +231,13 @@ describe('fetchLists', () => { ...@@ -233,14 +231,13 @@ describe('fetchLists', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('should commit mutations RECEIVE_BOARD_LISTS_FAILURE on failure', (done) => { it('should commit mutations RECEIVE_BOARD_LISTS_FAILURE on failure', () => {
jest.spyOn(gqlClient, 'query').mockResolvedValue(Promise.reject()); jest.spyOn(gqlClient, 'query').mockResolvedValue(Promise.reject());
testAction( return testAction(
actions.fetchLists, actions.fetchLists,
{}, {},
state, state,
...@@ -250,11 +247,10 @@ describe('fetchLists', () => { ...@@ -250,11 +247,10 @@ describe('fetchLists', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('dispatch createList action when backlog list does not exist and is not hidden', (done) => { it('dispatch createList action when backlog list does not exist and is not hidden', () => {
queryResponse = { queryResponse = {
data: { data: {
group: { group: {
...@@ -269,7 +265,7 @@ describe('fetchLists', () => { ...@@ -269,7 +265,7 @@ describe('fetchLists', () => {
}; };
jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse); jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse);
testAction( return testAction(
actions.fetchLists, actions.fetchLists,
{}, {},
state, state,
...@@ -280,7 +276,6 @@ describe('fetchLists', () => { ...@@ -280,7 +276,6 @@ describe('fetchLists', () => {
}, },
], ],
[{ type: 'createList', payload: { backlog: true } }], [{ type: 'createList', payload: { backlog: true } }],
done,
); );
}); });
...@@ -951,10 +946,10 @@ describe('fetchItemsForList', () => { ...@@ -951,10 +946,10 @@ describe('fetchItemsForList', () => {
}); });
}); });
it('should commit mutations REQUEST_ITEMS_FOR_LIST and RECEIVE_ITEMS_FOR_LIST_SUCCESS on success', (done) => { it('should commit mutations REQUEST_ITEMS_FOR_LIST and RECEIVE_ITEMS_FOR_LIST_SUCCESS on success', () => {
jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse); jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse);
testAction( return testAction(
actions.fetchItemsForList, actions.fetchItemsForList,
{ listId }, { listId },
state, state,
...@@ -973,14 +968,13 @@ describe('fetchItemsForList', () => { ...@@ -973,14 +968,13 @@ describe('fetchItemsForList', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('should commit mutations REQUEST_ITEMS_FOR_LIST and RECEIVE_ITEMS_FOR_LIST_FAILURE on failure', (done) => { it('should commit mutations REQUEST_ITEMS_FOR_LIST and RECEIVE_ITEMS_FOR_LIST_FAILURE on failure', () => {
jest.spyOn(gqlClient, 'query').mockResolvedValue(Promise.reject()); jest.spyOn(gqlClient, 'query').mockResolvedValue(Promise.reject());
testAction( return testAction(
actions.fetchItemsForList, actions.fetchItemsForList,
{ listId }, { listId },
state, state,
...@@ -996,7 +990,6 @@ describe('fetchItemsForList', () => { ...@@ -996,7 +990,6 @@ describe('fetchItemsForList', () => {
{ type: types.RECEIVE_ITEMS_FOR_LIST_FAILURE, payload: listId }, { type: types.RECEIVE_ITEMS_FOR_LIST_FAILURE, payload: listId },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -1398,8 +1391,8 @@ describe('setAssignees', () => { ...@@ -1398,8 +1391,8 @@ describe('setAssignees', () => {
const node = { username: 'name' }; const node = { username: 'name' };
describe('when succeeds', () => { describe('when succeeds', () => {
it('calls the correct mutation with the correct values', (done) => { it('calls the correct mutation with the correct values', () => {
testAction( return testAction(
actions.setAssignees, actions.setAssignees,
{ assignees: [node], iid: '1' }, { assignees: [node], iid: '1' },
{ commit: () => {} }, { commit: () => {} },
...@@ -1410,7 +1403,6 @@ describe('setAssignees', () => { ...@@ -1410,7 +1403,6 @@ describe('setAssignees', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -1728,7 +1720,7 @@ describe('setActiveItemSubscribed', () => { ...@@ -1728,7 +1720,7 @@ describe('setActiveItemSubscribed', () => {
projectPath: 'gitlab-org/gitlab-test', projectPath: 'gitlab-org/gitlab-test',
}; };
it('should commit subscribed status', (done) => { it('should commit subscribed status', () => {
jest.spyOn(gqlClient, 'mutate').mockResolvedValue({ jest.spyOn(gqlClient, 'mutate').mockResolvedValue({
data: { data: {
updateIssuableSubscription: { updateIssuableSubscription: {
...@@ -1746,7 +1738,7 @@ describe('setActiveItemSubscribed', () => { ...@@ -1746,7 +1738,7 @@ describe('setActiveItemSubscribed', () => {
value: subscribedState, value: subscribedState,
}; };
testAction( return testAction(
actions.setActiveItemSubscribed, actions.setActiveItemSubscribed,
input, input,
{ ...state, ...getters }, { ...state, ...getters },
...@@ -1757,7 +1749,6 @@ describe('setActiveItemSubscribed', () => { ...@@ -1757,7 +1749,6 @@ describe('setActiveItemSubscribed', () => {
}, },
], ],
[], [],
done,
); );
}); });
...@@ -1783,7 +1774,7 @@ describe('setActiveItemTitle', () => { ...@@ -1783,7 +1774,7 @@ describe('setActiveItemTitle', () => {
projectPath: 'h/b', projectPath: 'h/b',
}; };
it('should commit title after setting the issue', (done) => { it('should commit title after setting the issue', () => {
jest.spyOn(gqlClient, 'mutate').mockResolvedValue({ jest.spyOn(gqlClient, 'mutate').mockResolvedValue({
data: { data: {
updateIssuableTitle: { updateIssuableTitle: {
...@@ -1801,7 +1792,7 @@ describe('setActiveItemTitle', () => { ...@@ -1801,7 +1792,7 @@ describe('setActiveItemTitle', () => {
value: testTitle, value: testTitle,
}; };
testAction( return testAction(
actions.setActiveItemTitle, actions.setActiveItemTitle,
input, input,
{ ...state, ...getters }, { ...state, ...getters },
...@@ -1812,7 +1803,6 @@ describe('setActiveItemTitle', () => { ...@@ -1812,7 +1803,6 @@ describe('setActiveItemTitle', () => {
}, },
], ],
[], [],
done,
); );
}); });
...@@ -1829,14 +1819,14 @@ describe('setActiveItemConfidential', () => { ...@@ -1829,14 +1819,14 @@ describe('setActiveItemConfidential', () => {
const state = { boardItems: { [mockIssue.id]: mockIssue } }; const state = { boardItems: { [mockIssue.id]: mockIssue } };
const getters = { activeBoardItem: mockIssue }; const getters = { activeBoardItem: mockIssue };
it('set confidential value on board item', (done) => { it('set confidential value on board item', () => {
const payload = { const payload = {
itemId: getters.activeBoardItem.id, itemId: getters.activeBoardItem.id,
prop: 'confidential', prop: 'confidential',
value: true, value: true,
}; };
testAction( return testAction(
actions.setActiveItemConfidential, actions.setActiveItemConfidential,
true, true,
{ ...state, ...getters }, { ...state, ...getters },
...@@ -1847,7 +1837,6 @@ describe('setActiveItemConfidential', () => { ...@@ -1847,7 +1837,6 @@ describe('setActiveItemConfidential', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -1876,10 +1865,10 @@ describe('fetchGroupProjects', () => { ...@@ -1876,10 +1865,10 @@ describe('fetchGroupProjects', () => {
}, },
}; };
it('should commit mutations REQUEST_GROUP_PROJECTS and RECEIVE_GROUP_PROJECTS_SUCCESS on success', (done) => { it('should commit mutations REQUEST_GROUP_PROJECTS and RECEIVE_GROUP_PROJECTS_SUCCESS on success', () => {
jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse); jest.spyOn(gqlClient, 'query').mockResolvedValue(queryResponse);
testAction( return testAction(
actions.fetchGroupProjects, actions.fetchGroupProjects,
{}, {},
state, state,
...@@ -1894,14 +1883,13 @@ describe('fetchGroupProjects', () => { ...@@ -1894,14 +1883,13 @@ describe('fetchGroupProjects', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('should commit mutations REQUEST_GROUP_PROJECTS and RECEIVE_GROUP_PROJECTS_FAILURE on failure', (done) => { it('should commit mutations REQUEST_GROUP_PROJECTS and RECEIVE_GROUP_PROJECTS_FAILURE on failure', () => {
jest.spyOn(gqlClient, 'query').mockRejectedValue(); jest.spyOn(gqlClient, 'query').mockRejectedValue();
testAction( return testAction(
actions.fetchGroupProjects, actions.fetchGroupProjects,
{}, {},
state, state,
...@@ -1915,16 +1903,15 @@ describe('fetchGroupProjects', () => { ...@@ -1915,16 +1903,15 @@ describe('fetchGroupProjects', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('setSelectedProject', () => { describe('setSelectedProject', () => {
it('should commit mutation SET_SELECTED_PROJECT', (done) => { it('should commit mutation SET_SELECTED_PROJECT', () => {
const project = mockGroupProjects[0]; const project = mockGroupProjects[0];
testAction( return testAction(
actions.setSelectedProject, actions.setSelectedProject,
project, project,
{}, {},
...@@ -1935,7 +1922,6 @@ describe('setSelectedProject', () => { ...@@ -1935,7 +1922,6 @@ describe('setSelectedProject', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
......
...@@ -95,42 +95,51 @@ describe('apolloCaptchaLink', () => { ...@@ -95,42 +95,51 @@ describe('apolloCaptchaLink', () => {
return { operationName: 'operation', variables: {}, setContext: mockContext }; return { operationName: 'operation', variables: {}, setContext: mockContext };
} }
it('successful responses are passed through', (done) => { it('successful responses are passed through', () => {
setupLink(SUCCESS_RESPONSE); setupLink(SUCCESS_RESPONSE);
return new Promise((resolve) => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(SUCCESS_RESPONSE); expect(result).toEqual(SUCCESS_RESPONSE);
expect(mockLinkImplementation).toHaveBeenCalledTimes(1); expect(mockLinkImplementation).toHaveBeenCalledTimes(1);
expect(waitForCaptchaToBeSolved).not.toHaveBeenCalled(); expect(waitForCaptchaToBeSolved).not.toHaveBeenCalled();
done(); resolve();
});
}); });
}); });
it('non-spam related errors are passed through', (done) => { it('non-spam related errors are passed through', () => {
setupLink(NON_CAPTCHA_ERROR_RESPONSE); setupLink(NON_CAPTCHA_ERROR_RESPONSE);
return new Promise((resolve) => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(NON_CAPTCHA_ERROR_RESPONSE); expect(result).toEqual(NON_CAPTCHA_ERROR_RESPONSE);
expect(mockLinkImplementation).toHaveBeenCalledTimes(1); expect(mockLinkImplementation).toHaveBeenCalledTimes(1);
expect(mockContext).not.toHaveBeenCalled(); expect(mockContext).not.toHaveBeenCalled();
expect(waitForCaptchaToBeSolved).not.toHaveBeenCalled(); expect(waitForCaptchaToBeSolved).not.toHaveBeenCalled();
done(); resolve();
});
}); });
}); });
it('unresolvable spam errors are passed through', (done) => { it('unresolvable spam errors are passed through', () => {
setupLink(SPAM_ERROR_RESPONSE); setupLink(SPAM_ERROR_RESPONSE);
return new Promise((resolve) => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(SPAM_ERROR_RESPONSE); expect(result).toEqual(SPAM_ERROR_RESPONSE);
expect(mockLinkImplementation).toHaveBeenCalledTimes(1); expect(mockLinkImplementation).toHaveBeenCalledTimes(1);
expect(mockContext).not.toHaveBeenCalled(); expect(mockContext).not.toHaveBeenCalled();
expect(waitForCaptchaToBeSolved).not.toHaveBeenCalled(); expect(waitForCaptchaToBeSolved).not.toHaveBeenCalled();
done(); resolve();
});
}); });
}); });
describe('resolvable spam errors', () => { describe('resolvable spam errors', () => {
it('re-submits request with spam headers if the captcha modal was solved correctly', (done) => { it('re-submits request with spam headers if the captcha modal was solved correctly', () => {
waitForCaptchaToBeSolved.mockResolvedValue(CAPTCHA_RESPONSE); waitForCaptchaToBeSolved.mockResolvedValue(CAPTCHA_RESPONSE);
setupLink(CAPTCHA_ERROR_RESPONSE, SUCCESS_RESPONSE); setupLink(CAPTCHA_ERROR_RESPONSE, SUCCESS_RESPONSE);
return new Promise((resolve) => {
link.request(mockOperation()).subscribe((result) => { link.request(mockOperation()).subscribe((result) => {
expect(result).toEqual(SUCCESS_RESPONSE); expect(result).toEqual(SUCCESS_RESPONSE);
expect(waitForCaptchaToBeSolved).toHaveBeenCalledWith(CAPTCHA_SITE_KEY); expect(waitForCaptchaToBeSolved).toHaveBeenCalledWith(CAPTCHA_SITE_KEY);
...@@ -141,25 +150,28 @@ describe('apolloCaptchaLink', () => { ...@@ -141,25 +150,28 @@ describe('apolloCaptchaLink', () => {
}, },
}); });
expect(mockLinkImplementation).toHaveBeenCalledTimes(2); expect(mockLinkImplementation).toHaveBeenCalledTimes(2);
done(); resolve();
});
}); });
}); });
it('throws error if the captcha modal was not solved correctly', (done) => { it('throws error if the captcha modal was not solved correctly', () => {
const error = new UnsolvedCaptchaError(); const error = new UnsolvedCaptchaError();
waitForCaptchaToBeSolved.mockRejectedValue(error); waitForCaptchaToBeSolved.mockRejectedValue(error);
setupLink(CAPTCHA_ERROR_RESPONSE, SUCCESS_RESPONSE); setupLink(CAPTCHA_ERROR_RESPONSE, SUCCESS_RESPONSE);
return new Promise((resolve, reject) => {
link.request(mockOperation()).subscribe({ link.request(mockOperation()).subscribe({
next: done.catch, next: reject,
error: (result) => { error: (result) => {
expect(result).toEqual(error); expect(result).toEqual(error);
expect(waitForCaptchaToBeSolved).toHaveBeenCalledWith(CAPTCHA_SITE_KEY); expect(waitForCaptchaToBeSolved).toHaveBeenCalledWith(CAPTCHA_SITE_KEY);
expect(mockContext).not.toHaveBeenCalled(); expect(mockContext).not.toHaveBeenCalled();
expect(mockLinkImplementation).toHaveBeenCalledTimes(1); expect(mockLinkImplementation).toHaveBeenCalledTimes(1);
done(); resolve();
}, },
}); });
}); });
}); });
});
}); });
...@@ -86,10 +86,10 @@ describe('CI variable list store actions', () => { ...@@ -86,10 +86,10 @@ describe('CI variable list store actions', () => {
}); });
describe('deleteVariable', () => { describe('deleteVariable', () => {
it('dispatch correct actions on successful deleted variable', (done) => { it('dispatch correct actions on successful deleted variable', () => {
mock.onPatch(state.endpoint).reply(200); mock.onPatch(state.endpoint).reply(200);
testAction( return testAction(
actions.deleteVariable, actions.deleteVariable,
{}, {},
state, state,
...@@ -99,16 +99,13 @@ describe('CI variable list store actions', () => { ...@@ -99,16 +99,13 @@ describe('CI variable list store actions', () => {
{ type: 'receiveDeleteVariableSuccess' }, { type: 'receiveDeleteVariableSuccess' },
{ type: 'fetchVariables' }, { type: 'fetchVariables' },
], ],
() => {
done();
},
); );
}); });
it('should show flash error and set error in state on delete failure', (done) => { it('should show flash error and set error in state on delete failure', async () => {
mock.onPatch(state.endpoint).reply(500, ''); mock.onPatch(state.endpoint).reply(500, '');
testAction( await testAction(
actions.deleteVariable, actions.deleteVariable,
{}, {},
state, state,
...@@ -120,19 +117,16 @@ describe('CI variable list store actions', () => { ...@@ -120,19 +117,16 @@ describe('CI variable list store actions', () => {
payload: payloadError, payload: payloadError,
}, },
], ],
() => {
expect(createFlash).toHaveBeenCalled();
done();
},
); );
expect(createFlash).toHaveBeenCalled();
}); });
}); });
describe('updateVariable', () => { describe('updateVariable', () => {
it('dispatch correct actions on successful updated variable', (done) => { it('dispatch correct actions on successful updated variable', () => {
mock.onPatch(state.endpoint).reply(200); mock.onPatch(state.endpoint).reply(200);
testAction( return testAction(
actions.updateVariable, actions.updateVariable,
{}, {},
state, state,
...@@ -142,16 +136,13 @@ describe('CI variable list store actions', () => { ...@@ -142,16 +136,13 @@ describe('CI variable list store actions', () => {
{ type: 'receiveUpdateVariableSuccess' }, { type: 'receiveUpdateVariableSuccess' },
{ type: 'fetchVariables' }, { type: 'fetchVariables' },
], ],
() => {
done();
},
); );
}); });
it('should show flash error and set error in state on update failure', (done) => { it('should show flash error and set error in state on update failure', async () => {
mock.onPatch(state.endpoint).reply(500, ''); mock.onPatch(state.endpoint).reply(500, '');
testAction( await testAction(
actions.updateVariable, actions.updateVariable,
mockVariable, mockVariable,
state, state,
...@@ -163,19 +154,16 @@ describe('CI variable list store actions', () => { ...@@ -163,19 +154,16 @@ describe('CI variable list store actions', () => {
payload: payloadError, payload: payloadError,
}, },
], ],
() => {
expect(createFlash).toHaveBeenCalled();
done();
},
); );
expect(createFlash).toHaveBeenCalled();
}); });
}); });
describe('addVariable', () => { describe('addVariable', () => {
it('dispatch correct actions on successful added variable', (done) => { it('dispatch correct actions on successful added variable', () => {
mock.onPatch(state.endpoint).reply(200); mock.onPatch(state.endpoint).reply(200);
testAction( return testAction(
actions.addVariable, actions.addVariable,
{}, {},
state, state,
...@@ -185,16 +173,13 @@ describe('CI variable list store actions', () => { ...@@ -185,16 +173,13 @@ describe('CI variable list store actions', () => {
{ type: 'receiveAddVariableSuccess' }, { type: 'receiveAddVariableSuccess' },
{ type: 'fetchVariables' }, { type: 'fetchVariables' },
], ],
() => {
done();
},
); );
}); });
it('should show flash error and set error in state on add failure', (done) => { it('should show flash error and set error in state on add failure', async () => {
mock.onPatch(state.endpoint).reply(500, ''); mock.onPatch(state.endpoint).reply(500, '');
testAction( await testAction(
actions.addVariable, actions.addVariable,
{}, {},
state, state,
...@@ -206,19 +191,16 @@ describe('CI variable list store actions', () => { ...@@ -206,19 +191,16 @@ describe('CI variable list store actions', () => {
payload: payloadError, payload: payloadError,
}, },
], ],
() => {
expect(createFlash).toHaveBeenCalled();
done();
},
); );
expect(createFlash).toHaveBeenCalled();
}); });
}); });
describe('fetchVariables', () => { describe('fetchVariables', () => {
it('dispatch correct actions on fetchVariables', (done) => { it('dispatch correct actions on fetchVariables', () => {
mock.onGet(state.endpoint).reply(200, { variables: mockData.mockVariables }); mock.onGet(state.endpoint).reply(200, { variables: mockData.mockVariables });
testAction( return testAction(
actions.fetchVariables, actions.fetchVariables,
{}, {},
state, state,
...@@ -230,29 +212,24 @@ describe('CI variable list store actions', () => { ...@@ -230,29 +212,24 @@ describe('CI variable list store actions', () => {
payload: prepareDataForDisplay(mockData.mockVariables), payload: prepareDataForDisplay(mockData.mockVariables),
}, },
], ],
() => {
done();
},
); );
}); });
it('should show flash error and set error in state on fetch variables failure', (done) => { it('should show flash error and set error in state on fetch variables failure', async () => {
mock.onGet(state.endpoint).reply(500); mock.onGet(state.endpoint).reply(500);
testAction(actions.fetchVariables, {}, state, [], [{ type: 'requestVariables' }], () => { await testAction(actions.fetchVariables, {}, state, [], [{ type: 'requestVariables' }]);
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: 'There was an error fetching the variables.', message: 'There was an error fetching the variables.',
}); });
done();
});
}); });
}); });
describe('fetchEnvironments', () => { describe('fetchEnvironments', () => {
it('dispatch correct actions on fetchEnvironments', (done) => { it('dispatch correct actions on fetchEnvironments', () => {
Api.environments = jest.fn().mockResolvedValue({ data: mockData.mockEnvironments }); Api.environments = jest.fn().mockResolvedValue({ data: mockData.mockEnvironments });
testAction( return testAction(
actions.fetchEnvironments, actions.fetchEnvironments,
{}, {},
state, state,
...@@ -264,28 +241,17 @@ describe('CI variable list store actions', () => { ...@@ -264,28 +241,17 @@ describe('CI variable list store actions', () => {
payload: prepareEnvironments(mockData.mockEnvironments), payload: prepareEnvironments(mockData.mockEnvironments),
}, },
], ],
() => {
done();
},
); );
}); });
it('should show flash error and set error in state on fetch environments failure', (done) => { it('should show flash error and set error in state on fetch environments failure', async () => {
Api.environments = jest.fn().mockRejectedValue(); Api.environments = jest.fn().mockRejectedValue();
testAction( await testAction(actions.fetchEnvironments, {}, state, [], [{ type: 'requestEnvironments' }]);
actions.fetchEnvironments,
{},
state,
[],
[{ type: 'requestEnvironments' }],
() => {
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: 'There was an error fetching the environments information.', message: 'There was an error fetching the environments information.',
}); });
done();
},
);
}); });
}); });
......
...@@ -24,14 +24,12 @@ describe('Clusters store actions', () => { ...@@ -24,14 +24,12 @@ describe('Clusters store actions', () => {
captureException.mockRestore(); captureException.mockRestore();
}); });
it('should report sentry error', (done) => { it('should report sentry error', async () => {
const sentryError = new Error('New Sentry Error'); const sentryError = new Error('New Sentry Error');
const tag = 'sentryErrorTag'; const tag = 'sentryErrorTag';
testAction(actions.reportSentryError, { error: sentryError, tag }, {}, [], [], () => { await testAction(actions.reportSentryError, { error: sentryError, tag }, {}, [], []);
expect(captureException).toHaveBeenCalledWith(sentryError); expect(captureException).toHaveBeenCalledWith(sentryError);
done();
});
}); });
}); });
...@@ -62,10 +60,10 @@ describe('Clusters store actions', () => { ...@@ -62,10 +60,10 @@ describe('Clusters store actions', () => {
afterEach(() => mock.restore()); afterEach(() => mock.restore());
it('should commit SET_CLUSTERS_DATA with received response', (done) => { it('should commit SET_CLUSTERS_DATA with received response', () => {
mock.onGet().reply(200, apiData, headers); mock.onGet().reply(200, apiData, headers);
testAction( return testAction(
actions.fetchClusters, actions.fetchClusters,
{ endpoint: apiData.endpoint }, { endpoint: apiData.endpoint },
{}, {},
...@@ -75,14 +73,13 @@ describe('Clusters store actions', () => { ...@@ -75,14 +73,13 @@ describe('Clusters store actions', () => {
{ type: types.SET_LOADING_CLUSTERS, payload: false }, { type: types.SET_LOADING_CLUSTERS, payload: false },
], ],
[], [],
() => done(),
); );
}); });
it('should show flash on API error', (done) => { it('should show flash on API error', async () => {
mock.onGet().reply(400, 'Not Found'); mock.onGet().reply(400, 'Not Found');
testAction( await testAction(
actions.fetchClusters, actions.fetchClusters,
{ endpoint: apiData.endpoint }, { endpoint: apiData.endpoint },
{}, {},
...@@ -100,13 +97,10 @@ describe('Clusters store actions', () => { ...@@ -100,13 +97,10 @@ describe('Clusters store actions', () => {
}, },
}, },
], ],
() => { );
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: expect.stringMatching('error'), message: expect.stringMatching('error'),
}); });
done();
},
);
}); });
describe('multiple api requests', () => { describe('multiple api requests', () => {
...@@ -128,8 +122,8 @@ describe('Clusters store actions', () => { ...@@ -128,8 +122,8 @@ describe('Clusters store actions', () => {
pollStop.mockRestore(); pollStop.mockRestore();
}); });
it('should stop polling after MAX Requests', (done) => { it('should stop polling after MAX Requests', async () => {
testAction( await testAction(
actions.fetchClusters, actions.fetchClusters,
{ endpoint: apiData.endpoint }, { endpoint: apiData.endpoint },
{}, {},
...@@ -139,12 +133,12 @@ describe('Clusters store actions', () => { ...@@ -139,12 +133,12 @@ describe('Clusters store actions', () => {
{ type: types.SET_LOADING_CLUSTERS, payload: false }, { type: types.SET_LOADING_CLUSTERS, payload: false },
], ],
[], [],
() => { );
expect(pollRequest).toHaveBeenCalledTimes(1); expect(pollRequest).toHaveBeenCalledTimes(1);
expect(pollStop).toHaveBeenCalledTimes(0); expect(pollStop).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(pollInterval); jest.advanceTimersByTime(pollInterval);
waitForPromises() return waitForPromises()
.then(() => { .then(() => {
expect(pollRequest).toHaveBeenCalledTimes(2); expect(pollRequest).toHaveBeenCalledTimes(2);
expect(pollStop).toHaveBeenCalledTimes(0); expect(pollStop).toHaveBeenCalledTimes(0);
...@@ -168,18 +162,14 @@ describe('Clusters store actions', () => { ...@@ -168,18 +162,14 @@ describe('Clusters store actions', () => {
// Additional poll requests are not made once pollStop is called // Additional poll requests are not made once pollStop is called
expect(pollRequest).toHaveBeenCalledTimes(MAX_REQUESTS + 1); expect(pollRequest).toHaveBeenCalledTimes(MAX_REQUESTS + 1);
expect(pollStop).toHaveBeenCalledTimes(1); expect(pollStop).toHaveBeenCalledTimes(1);
}) });
.then(done)
.catch(done.fail);
},
);
}); });
it('should stop polling and report to Sentry when data is invalid', (done) => { it('should stop polling and report to Sentry when data is invalid', async () => {
const badApiResponse = { clusters: {} }; const badApiResponse = { clusters: {} };
mock.onGet().reply(200, badApiResponse, pollHeaders); mock.onGet().reply(200, badApiResponse, pollHeaders);
testAction( await testAction(
actions.fetchClusters, actions.fetchClusters,
{ endpoint: apiData.endpoint }, { endpoint: apiData.endpoint },
{}, {},
...@@ -202,12 +192,9 @@ describe('Clusters store actions', () => { ...@@ -202,12 +192,9 @@ describe('Clusters store actions', () => {
}, },
}, },
], ],
() => { );
expect(pollRequest).toHaveBeenCalledTimes(1); expect(pollRequest).toHaveBeenCalledTimes(1);
expect(pollStop).toHaveBeenCalledTimes(1); expect(pollStop).toHaveBeenCalledTimes(1);
done();
},
);
}); });
}); });
}); });
......
...@@ -10,14 +10,13 @@ describe('Code navigation actions', () => { ...@@ -10,14 +10,13 @@ describe('Code navigation actions', () => {
const wrapTextNodes = true; const wrapTextNodes = true;
describe('setInitialData', () => { describe('setInitialData', () => {
it('commits SET_INITIAL_DATA', (done) => { it('commits SET_INITIAL_DATA', () => {
testAction( return testAction(
actions.setInitialData, actions.setInitialData,
{ projectPath: 'test', wrapTextNodes }, { projectPath: 'test', wrapTextNodes },
{}, {},
[{ type: 'SET_INITIAL_DATA', payload: { projectPath: 'test', wrapTextNodes } }], [{ type: 'SET_INITIAL_DATA', payload: { projectPath: 'test', wrapTextNodes } }],
[], [],
done,
); );
}); });
}); });
...@@ -59,8 +58,8 @@ describe('Code navigation actions', () => { ...@@ -59,8 +58,8 @@ describe('Code navigation actions', () => {
]); ]);
}); });
it('commits REQUEST_DATA_SUCCESS with normalized data', (done) => { it('commits REQUEST_DATA_SUCCESS with normalized data', () => {
testAction( return testAction(
actions.fetchData, actions.fetchData,
null, null,
state, state,
...@@ -82,12 +81,11 @@ describe('Code navigation actions', () => { ...@@ -82,12 +81,11 @@ describe('Code navigation actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('calls addInteractionClass with data', (done) => { it('calls addInteractionClass with data', () => {
testAction( return testAction(
actions.fetchData, actions.fetchData,
null, null,
state, state,
...@@ -109,8 +107,7 @@ describe('Code navigation actions', () => { ...@@ -109,8 +107,7 @@ describe('Code navigation actions', () => {
}, },
], ],
[], [],
) ).then(() => {
.then(() => {
expect(addInteractionClass).toHaveBeenCalledWith({ expect(addInteractionClass).toHaveBeenCalledWith({
path: 'index.js', path: 'index.js',
d: { d: {
...@@ -120,9 +117,7 @@ describe('Code navigation actions', () => { ...@@ -120,9 +117,7 @@ describe('Code navigation actions', () => {
}, },
wrapTextNodes, wrapTextNodes,
}); });
}) });
.then(done)
.catch(done.fail);
}); });
}); });
...@@ -131,14 +126,13 @@ describe('Code navigation actions', () => { ...@@ -131,14 +126,13 @@ describe('Code navigation actions', () => {
mock.onGet(codeNavigationPath).replyOnce(500); mock.onGet(codeNavigationPath).replyOnce(500);
}); });
it('dispatches requestDataError', (done) => { it('dispatches requestDataError', () => {
testAction( return testAction(
actions.fetchData, actions.fetchData,
null, null,
state, state,
[{ type: 'REQUEST_DATA' }], [{ type: 'REQUEST_DATA' }],
[{ type: 'requestDataError' }], [{ type: 'requestDataError' }],
done,
); );
}); });
}); });
...@@ -186,20 +180,20 @@ describe('Code navigation actions', () => { ...@@ -186,20 +180,20 @@ describe('Code navigation actions', () => {
target = document.querySelector('.js-test'); target = document.querySelector('.js-test');
}); });
it('returns early when no data exists', (done) => { it('returns early when no data exists', () => {
testAction(actions.showDefinition, { target }, {}, [], [], done); return testAction(actions.showDefinition, { target }, {}, [], []);
}); });
it('commits SET_CURRENT_DEFINITION when target is not code navitation element', (done) => { it('commits SET_CURRENT_DEFINITION when target is not code navitation element', () => {
testAction(actions.showDefinition, { target }, { data: {} }, [], [], done); return testAction(actions.showDefinition, { target }, { data: {} }, [], []);
}); });
it('commits SET_CURRENT_DEFINITION with LSIF data', (done) => { it('commits SET_CURRENT_DEFINITION with LSIF data', () => {
target.classList.add('js-code-navigation'); target.classList.add('js-code-navigation');
target.setAttribute('data-line-index', '0'); target.setAttribute('data-line-index', '0');
target.setAttribute('data-char-index', '0'); target.setAttribute('data-char-index', '0');
testAction( return testAction(
actions.showDefinition, actions.showDefinition,
{ target }, { target },
{ data: { 'index.js': { '0:0': { hover: 'test' } } } }, { data: { 'index.js': { '0:0': { hover: 'test' } } } },
...@@ -214,7 +208,6 @@ describe('Code navigation actions', () => { ...@@ -214,7 +208,6 @@ describe('Code navigation actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
......
...@@ -120,13 +120,14 @@ describe('Pipelines table in Commits and Merge requests', () => { ...@@ -120,13 +120,14 @@ describe('Pipelines table in Commits and Merge requests', () => {
}); });
describe('pipeline badge counts', () => { describe('pipeline badge counts', () => {
it('should receive update-pipelines-count event', (done) => { it('should receive update-pipelines-count event', () => {
const element = document.createElement('div'); const element = document.createElement('div');
document.body.appendChild(element); document.body.appendChild(element);
return new Promise((resolve) => {
element.addEventListener('update-pipelines-count', (event) => { element.addEventListener('update-pipelines-count', (event) => {
expect(event.detail.pipelineCount).toEqual(10); expect(event.detail.pipelineCount).toEqual(10);
done(); resolve();
}); });
createComponent(); createComponent();
...@@ -136,6 +137,7 @@ describe('Pipelines table in Commits and Merge requests', () => { ...@@ -136,6 +137,7 @@ describe('Pipelines table in Commits and Merge requests', () => {
}); });
}); });
}); });
});
describe('run pipeline button', () => { describe('run pipeline button', () => {
let pipelineCopy; let pipelineCopy;
......
...@@ -200,13 +200,15 @@ describe('content_editor/extensions/attachment', () => { ...@@ -200,13 +200,15 @@ describe('content_editor/extensions/attachment', () => {
}); });
}); });
it('emits an alert event that includes an error message', (done) => { it('emits an alert event that includes an error message', () => {
tiptapEditor.commands.uploadAttachment({ file }); tiptapEditor.commands.uploadAttachment({ file });
return new Promise((resolve) => {
eventHub.$on('alert', ({ message, variant }) => { eventHub.$on('alert', ({ message, variant }) => {
expect(variant).toBe(VARIANT_DANGER); expect(variant).toBe(VARIANT_DANGER);
expect(message).toBe('An error occurred while uploading the file. Please try again.'); expect(message).toBe('An error occurred while uploading the file. Please try again.');
done(); resolve();
});
}); });
}); });
}); });
...@@ -277,13 +279,12 @@ describe('content_editor/extensions/attachment', () => { ...@@ -277,13 +279,12 @@ describe('content_editor/extensions/attachment', () => {
}); });
}); });
it('emits an alert event that includes an error message', (done) => { it('emits an alert event that includes an error message', () => {
tiptapEditor.commands.uploadAttachment({ file: attachmentFile }); tiptapEditor.commands.uploadAttachment({ file: attachmentFile });
eventHub.$on('alert', ({ message, variant }) => { eventHub.$on('alert', ({ message, variant }) => {
expect(variant).toBe(VARIANT_DANGER); expect(variant).toBe(VARIANT_DANGER);
expect(message).toBe('An error occurred while uploading the file. Please try again.'); expect(message).toBe('An error occurred while uploading the file. Please try again.');
done();
}); });
}); });
}); });
......
...@@ -17,10 +17,14 @@ describe('Contributors store actions', () => { ...@@ -17,10 +17,14 @@ describe('Contributors store actions', () => {
mock = new MockAdapter(axios); mock = new MockAdapter(axios);
}); });
it('should commit SET_CHART_DATA with received response', (done) => { afterEach(() => {
mock.restore();
});
it('should commit SET_CHART_DATA with received response', () => {
mock.onGet().reply(200, chartData); mock.onGet().reply(200, chartData);
testAction( return testAction(
actions.fetchChartData, actions.fetchChartData,
{ endpoint }, { endpoint },
{}, {},
...@@ -30,30 +34,22 @@ describe('Contributors store actions', () => { ...@@ -30,30 +34,22 @@ describe('Contributors store actions', () => {
{ type: types.SET_LOADING_STATE, payload: false }, { type: types.SET_LOADING_STATE, payload: false },
], ],
[], [],
() => {
mock.restore();
done();
},
); );
}); });
it('should show flash on API error', (done) => { it('should show flash on API error', async () => {
mock.onGet().reply(400, 'Not Found'); mock.onGet().reply(400, 'Not Found');
testAction( await testAction(
actions.fetchChartData, actions.fetchChartData,
{ endpoint }, { endpoint },
{}, {},
[{ type: types.SET_LOADING_STATE, payload: true }], [{ type: types.SET_LOADING_STATE, payload: true }],
[], [],
() => { );
expect(createFlash).toHaveBeenCalledWith({ expect(createFlash).toHaveBeenCalledWith({
message: expect.stringMatching('error'), message: expect.stringMatching('error'),
}); });
mock.restore();
done();
},
);
}); });
}); });
}); });
...@@ -14,53 +14,49 @@ import { ...@@ -14,53 +14,49 @@ import {
describe('GCP Cluster Dropdown Store Actions', () => { describe('GCP Cluster Dropdown Store Actions', () => {
describe('setProject', () => { describe('setProject', () => {
it('should set project', (done) => { it('should set project', () => {
testAction( return testAction(
actions.setProject, actions.setProject,
selectedProjectMock, selectedProjectMock,
{ selectedProject: {} }, { selectedProject: {} },
[{ type: 'SET_PROJECT', payload: selectedProjectMock }], [{ type: 'SET_PROJECT', payload: selectedProjectMock }],
[], [],
done,
); );
}); });
}); });
describe('setZone', () => { describe('setZone', () => {
it('should set zone', (done) => { it('should set zone', () => {
testAction( return testAction(
actions.setZone, actions.setZone,
selectedZoneMock, selectedZoneMock,
{ selectedZone: '' }, { selectedZone: '' },
[{ type: 'SET_ZONE', payload: selectedZoneMock }], [{ type: 'SET_ZONE', payload: selectedZoneMock }],
[], [],
done,
); );
}); });
}); });
describe('setMachineType', () => { describe('setMachineType', () => {
it('should set machine type', (done) => { it('should set machine type', () => {
testAction( return testAction(
actions.setMachineType, actions.setMachineType,
selectedMachineTypeMock, selectedMachineTypeMock,
{ selectedMachineType: '' }, { selectedMachineType: '' },
[{ type: 'SET_MACHINE_TYPE', payload: selectedMachineTypeMock }], [{ type: 'SET_MACHINE_TYPE', payload: selectedMachineTypeMock }],
[], [],
done,
); );
}); });
}); });
describe('setIsValidatingProjectBilling', () => { describe('setIsValidatingProjectBilling', () => {
it('should set machine type', (done) => { it('should set machine type', () => {
testAction( return testAction(
actions.setIsValidatingProjectBilling, actions.setIsValidatingProjectBilling,
true, true,
{ isValidatingProjectBilling: null }, { isValidatingProjectBilling: null },
[{ type: 'SET_IS_VALIDATING_PROJECT_BILLING', payload: true }], [{ type: 'SET_IS_VALIDATING_PROJECT_BILLING', payload: true }],
[], [],
done,
); );
}); });
}); });
...@@ -94,8 +90,8 @@ describe('GCP Cluster Dropdown Store Actions', () => { ...@@ -94,8 +90,8 @@ describe('GCP Cluster Dropdown Store Actions', () => {
}); });
describe('validateProjectBilling', () => { describe('validateProjectBilling', () => {
it('checks project billing status from Google API', (done) => { it('checks project billing status from Google API', () => {
testAction( return testAction(
actions.validateProjectBilling, actions.validateProjectBilling,
true, true,
{ {
...@@ -110,7 +106,6 @@ describe('GCP Cluster Dropdown Store Actions', () => { ...@@ -110,7 +106,6 @@ describe('GCP Cluster Dropdown Store Actions', () => {
{ type: 'SET_PROJECT_BILLING_STATUS', payload: true }, { type: 'SET_PROJECT_BILLING_STATUS', payload: true },
], ],
[{ type: 'setIsValidatingProjectBilling', payload: false }], [{ type: 'setIsValidatingProjectBilling', payload: false }],
done,
); );
}); });
}); });
......
...@@ -98,7 +98,7 @@ describe('DiffLineNoteForm', () => { ...@@ -98,7 +98,7 @@ describe('DiffLineNoteForm', () => {
}); });
describe('saveNoteForm', () => { describe('saveNoteForm', () => {
it('should call saveNote action with proper params', (done) => { it('should call saveNote action with proper params', async () => {
const saveDiffDiscussionSpy = jest const saveDiffDiscussionSpy = jest
.spyOn(wrapper.vm, 'saveDiffDiscussion') .spyOn(wrapper.vm, 'saveDiffDiscussion')
.mockReturnValue(Promise.resolve()); .mockReturnValue(Promise.resolve());
...@@ -123,16 +123,11 @@ describe('DiffLineNoteForm', () => { ...@@ -123,16 +123,11 @@ describe('DiffLineNoteForm', () => {
lineRange, lineRange,
}; };
wrapper.vm await wrapper.vm.handleSaveNote('note body');
.handleSaveNote('note body')
.then(() => {
expect(saveDiffDiscussionSpy).toHaveBeenCalledWith({ expect(saveDiffDiscussionSpy).toHaveBeenCalledWith({
note: 'note body', note: 'note body',
formData, formData,
}); });
})
.then(done)
.catch(done.fail);
}); });
}); });
}); });
......
...@@ -9,46 +9,7 @@ import { ...@@ -9,46 +9,7 @@ import {
INLINE_DIFF_VIEW_TYPE, INLINE_DIFF_VIEW_TYPE,
PARALLEL_DIFF_VIEW_TYPE, PARALLEL_DIFF_VIEW_TYPE,
} from '~/diffs/constants'; } from '~/diffs/constants';
import { import * as diffActions from '~/diffs/store/actions';
setBaseConfig,
fetchDiffFilesBatch,
fetchDiffFilesMeta,
fetchCoverageFiles,
assignDiscussionsToDiff,
removeDiscussionsFromDiff,
startRenderDiffsQueue,
setInlineDiffViewType,
setParallelDiffViewType,
showCommentForm,
cancelCommentForm,
loadMoreLines,
scrollToLineIfNeededInline,
scrollToLineIfNeededParallel,
loadCollapsedDiff,
toggleFileDiscussions,
saveDiffDiscussion,
setHighlightedRow,
toggleTreeOpen,
scrollToFile,
setShowTreeList,
renderFileForDiscussionId,
setRenderTreeList,
setShowWhitespace,
setRenderIt,
receiveFullDiffError,
fetchFullDiff,
toggleFullDiff,
switchToFullDiffFromRenamedFile,
setFileCollapsedByUser,
setExpandedDiffLines,
setSuggestPopoverDismissed,
changeCurrentCommit,
moveToNeighboringCommit,
setCurrentDiffFileIdFromNote,
navigateToDiffFileIndex,
setFileByFile,
reviewFile,
} from '~/diffs/store/actions';
import * as types from '~/diffs/store/mutation_types'; import * as types from '~/diffs/store/mutation_types';
import * as utils from '~/diffs/store/utils'; import * as utils from '~/diffs/store/utils';
import * as treeWorkerUtils from '~/diffs/utils/tree_worker_utils'; import * as treeWorkerUtils from '~/diffs/utils/tree_worker_utils';
...@@ -62,6 +23,8 @@ import { diffMetadata } from '../mock_data/diff_metadata'; ...@@ -62,6 +23,8 @@ import { diffMetadata } from '../mock_data/diff_metadata';
jest.mock('~/flash'); jest.mock('~/flash');
describe('DiffsStoreActions', () => { describe('DiffsStoreActions', () => {
let mock;
useLocalStorageSpy(); useLocalStorageSpy();
const originalMethods = { const originalMethods = {
...@@ -83,15 +46,20 @@ describe('DiffsStoreActions', () => { ...@@ -83,15 +46,20 @@ describe('DiffsStoreActions', () => {
}); });
}); });
beforeEach(() => {
mock = new MockAdapter(axios);
});
afterEach(() => { afterEach(() => {
['requestAnimationFrame', 'requestIdleCallback'].forEach((method) => { ['requestAnimationFrame', 'requestIdleCallback'].forEach((method) => {
global[method] = originalMethods[method]; global[method] = originalMethods[method];
}); });
createFlash.mockClear(); createFlash.mockClear();
mock.restore();
}); });
describe('setBaseConfig', () => { describe('setBaseConfig', () => {
it('should set given endpoint and project path', (done) => { it('should set given endpoint and project path', () => {
const endpoint = '/diffs/set/endpoint'; const endpoint = '/diffs/set/endpoint';
const endpointMetadata = '/diffs/set/endpoint/metadata'; const endpointMetadata = '/diffs/set/endpoint/metadata';
const endpointBatch = '/diffs/set/endpoint/batch'; const endpointBatch = '/diffs/set/endpoint/batch';
...@@ -104,8 +72,8 @@ describe('DiffsStoreActions', () => { ...@@ -104,8 +72,8 @@ describe('DiffsStoreActions', () => {
b: ['y', 'hash:a'], b: ['y', 'hash:a'],
}; };
testAction( return testAction(
setBaseConfig, diffActions.setBaseConfig,
{ {
endpoint, endpoint,
endpointBatch, endpointBatch,
...@@ -153,23 +121,12 @@ describe('DiffsStoreActions', () => { ...@@ -153,23 +121,12 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('fetchDiffFilesBatch', () => { describe('fetchDiffFilesBatch', () => {
let mock; it('should fetch batch diff files', () => {
beforeEach(() => {
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
});
it('should fetch batch diff files', (done) => {
const endpointBatch = '/fetch/diffs_batch'; const endpointBatch = '/fetch/diffs_batch';
const res1 = { diff_files: [{ file_hash: 'test' }], pagination: { total_pages: 7 } }; const res1 = { diff_files: [{ file_hash: 'test' }], pagination: { total_pages: 7 } };
const res2 = { diff_files: [{ file_hash: 'test2' }], pagination: { total_pages: 7 } }; const res2 = { diff_files: [{ file_hash: 'test2' }], pagination: { total_pages: 7 } };
...@@ -199,8 +156,8 @@ describe('DiffsStoreActions', () => { ...@@ -199,8 +156,8 @@ describe('DiffsStoreActions', () => {
) )
.reply(200, res2); .reply(200, res2);
testAction( return testAction(
fetchDiffFilesBatch, diffActions.fetchDiffFilesBatch,
{}, {},
{ endpointBatch, diffViewType: 'inline', diffFiles: [] }, { endpointBatch, diffViewType: 'inline', diffFiles: [] },
[ [
...@@ -216,7 +173,6 @@ describe('DiffsStoreActions', () => { ...@@ -216,7 +173,6 @@ describe('DiffsStoreActions', () => {
{ type: types.SET_BATCH_LOADING_STATE, payload: 'error' }, { type: types.SET_BATCH_LOADING_STATE, payload: 'error' },
], ],
[{ type: 'startRenderDiffsQueue' }, { type: 'startRenderDiffsQueue' }], [{ type: 'startRenderDiffsQueue' }, { type: 'startRenderDiffsQueue' }],
done,
); );
}); });
...@@ -229,7 +185,8 @@ describe('DiffsStoreActions', () => { ...@@ -229,7 +185,8 @@ describe('DiffsStoreActions', () => {
({ viewStyle, otherView }) => { ({ viewStyle, otherView }) => {
const endpointBatch = '/fetch/diffs_batch'; const endpointBatch = '/fetch/diffs_batch';
fetchDiffFilesBatch({ diffActions
.fetchDiffFilesBatch({
commit: () => {}, commit: () => {},
state: { state: {
endpointBatch: `${endpointBatch}?view=${otherView}`, endpointBatch: `${endpointBatch}?view=${otherView}`,
...@@ -248,19 +205,16 @@ describe('DiffsStoreActions', () => { ...@@ -248,19 +205,16 @@ describe('DiffsStoreActions', () => {
describe('fetchDiffFilesMeta', () => { describe('fetchDiffFilesMeta', () => {
const endpointMetadata = '/fetch/diffs_metadata.json?view=inline'; const endpointMetadata = '/fetch/diffs_metadata.json?view=inline';
const noFilesData = { ...diffMetadata }; const noFilesData = { ...diffMetadata };
let mock;
beforeEach(() => { beforeEach(() => {
mock = new MockAdapter(axios);
delete noFilesData.diff_files; delete noFilesData.diff_files;
mock.onGet(endpointMetadata).reply(200, diffMetadata); mock.onGet(endpointMetadata).reply(200, diffMetadata);
}); });
it('should fetch diff meta information', (done) => { it('should fetch diff meta information', () => {
testAction( return testAction(
fetchDiffFilesMeta, diffActions.fetchDiffFilesMeta,
{}, {},
{ endpointMetadata, diffViewType: 'inline' }, { endpointMetadata, diffViewType: 'inline' },
[ [
...@@ -275,55 +229,41 @@ describe('DiffsStoreActions', () => { ...@@ -275,55 +229,41 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
() => {
mock.restore();
done();
},
); );
}); });
}); });
describe('fetchCoverageFiles', () => { describe('fetchCoverageFiles', () => {
let mock;
const endpointCoverage = '/fetch'; const endpointCoverage = '/fetch';
beforeEach(() => { it('should commit SET_COVERAGE_DATA with received response', () => {
mock = new MockAdapter(axios);
});
afterEach(() => mock.restore());
it('should commit SET_COVERAGE_DATA with received response', (done) => {
const data = { files: { 'app.js': { 1: 0, 2: 1 } } }; const data = { files: { 'app.js': { 1: 0, 2: 1 } } };
mock.onGet(endpointCoverage).reply(200, { data }); mock.onGet(endpointCoverage).reply(200, { data });
testAction( return testAction(
fetchCoverageFiles, diffActions.fetchCoverageFiles,
{}, {},
{ endpointCoverage }, { endpointCoverage },
[{ type: types.SET_COVERAGE_DATA, payload: { data } }], [{ type: types.SET_COVERAGE_DATA, payload: { data } }],
[], [],
done,
); );
}); });
it('should show flash on API error', (done) => { it('should show flash on API error', async () => {
mock.onGet(endpointCoverage).reply(400); mock.onGet(endpointCoverage).reply(400);
testAction(fetchCoverageFiles, {}, { endpointCoverage }, [], [], () => { await testAction(diffActions.fetchCoverageFiles, {}, { endpointCoverage }, [], []);
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();
});
}); });
}); });
describe('setHighlightedRow', () => { describe('setHighlightedRow', () => {
it('should mark currently selected diff and set lineHash and fileHash of highlightedRow', () => { it('should mark currently selected diff and set lineHash and fileHash of highlightedRow', () => {
testAction(setHighlightedRow, 'ABC_123', {}, [ return testAction(diffActions.setHighlightedRow, 'ABC_123', {}, [
{ type: types.SET_HIGHLIGHTED_ROW, payload: 'ABC_123' }, { type: types.SET_HIGHLIGHTED_ROW, payload: 'ABC_123' },
{ type: types.SET_CURRENT_DIFF_FILE, payload: 'ABC' }, { type: types.SET_CURRENT_DIFF_FILE, payload: 'ABC' },
]); ]);
...@@ -335,7 +275,7 @@ describe('DiffsStoreActions', () => { ...@@ -335,7 +275,7 @@ describe('DiffsStoreActions', () => {
window.location.hash = ''; window.location.hash = '';
}); });
it('should merge discussions into diffs', (done) => { it('should merge discussions into diffs', () => {
window.location.hash = 'ABC_123'; window.location.hash = 'ABC_123';
const state = { const state = {
...@@ -397,8 +337,8 @@ describe('DiffsStoreActions', () => { ...@@ -397,8 +337,8 @@ describe('DiffsStoreActions', () => {
const discussions = [singleDiscussion]; const discussions = [singleDiscussion];
testAction( return testAction(
assignDiscussionsToDiff, diffActions.assignDiscussionsToDiff,
discussions, discussions,
state, state,
[ [
...@@ -425,26 +365,24 @@ describe('DiffsStoreActions', () => { ...@@ -425,26 +365,24 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('dispatches setCurrentDiffFileIdFromNote with note ID', (done) => { it('dispatches setCurrentDiffFileIdFromNote with note ID', () => {
window.location.hash = 'note_123'; window.location.hash = 'note_123';
testAction( return testAction(
assignDiscussionsToDiff, diffActions.assignDiscussionsToDiff,
[], [],
{ diffFiles: [] }, { diffFiles: [] },
[], [],
[{ type: 'setCurrentDiffFileIdFromNote', payload: '123' }], [{ type: 'setCurrentDiffFileIdFromNote', payload: '123' }],
done,
); );
}); });
}); });
describe('removeDiscussionsFromDiff', () => { describe('removeDiscussionsFromDiff', () => {
it('should remove discussions from diffs', (done) => { it('should remove discussions from diffs', () => {
const state = { const state = {
diffFiles: [ diffFiles: [
{ {
...@@ -480,8 +418,8 @@ describe('DiffsStoreActions', () => { ...@@ -480,8 +418,8 @@ describe('DiffsStoreActions', () => {
line_code: 'ABC_1_1', line_code: 'ABC_1_1',
}; };
testAction( return testAction(
removeDiscussionsFromDiff, diffActions.removeDiscussionsFromDiff,
singleDiscussion, singleDiscussion,
state, state,
[ [
...@@ -495,7 +433,6 @@ describe('DiffsStoreActions', () => { ...@@ -495,7 +433,6 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -528,7 +465,7 @@ describe('DiffsStoreActions', () => { ...@@ -528,7 +465,7 @@ describe('DiffsStoreActions', () => {
}); });
}; };
startRenderDiffsQueue({ state, commit: pseudoCommit }); diffActions.startRenderDiffsQueue({ state, commit: pseudoCommit });
expect(state.diffFiles[0].renderIt).toBe(true); expect(state.diffFiles[0].renderIt).toBe(true);
expect(state.diffFiles[1].renderIt).toBe(true); expect(state.diffFiles[1].renderIt).toBe(true);
...@@ -536,69 +473,61 @@ describe('DiffsStoreActions', () => { ...@@ -536,69 +473,61 @@ describe('DiffsStoreActions', () => {
}); });
describe('setInlineDiffViewType', () => { describe('setInlineDiffViewType', () => {
it('should set diff view type to inline and also set the cookie properly', (done) => { it('should set diff view type to inline and also set the cookie properly', async () => {
testAction( await testAction(
setInlineDiffViewType, diffActions.setInlineDiffViewType,
null, null,
{}, {},
[{ type: types.SET_DIFF_VIEW_TYPE, payload: INLINE_DIFF_VIEW_TYPE }], [{ type: types.SET_DIFF_VIEW_TYPE, payload: INLINE_DIFF_VIEW_TYPE }],
[], [],
() => {
expect(Cookies.get('diff_view')).toEqual(INLINE_DIFF_VIEW_TYPE);
done();
},
); );
expect(Cookies.get('diff_view')).toEqual(INLINE_DIFF_VIEW_TYPE);
}); });
}); });
describe('setParallelDiffViewType', () => { describe('setParallelDiffViewType', () => {
it('should set diff view type to parallel and also set the cookie properly', (done) => { it('should set diff view type to parallel and also set the cookie properly', async () => {
testAction( await testAction(
setParallelDiffViewType, diffActions.setParallelDiffViewType,
null, null,
{}, {},
[{ type: types.SET_DIFF_VIEW_TYPE, payload: PARALLEL_DIFF_VIEW_TYPE }], [{ type: types.SET_DIFF_VIEW_TYPE, payload: PARALLEL_DIFF_VIEW_TYPE }],
[], [],
() => {
expect(Cookies.get(DIFF_VIEW_COOKIE_NAME)).toEqual(PARALLEL_DIFF_VIEW_TYPE);
done();
},
); );
expect(Cookies.get(DIFF_VIEW_COOKIE_NAME)).toEqual(PARALLEL_DIFF_VIEW_TYPE);
}); });
}); });
describe('showCommentForm', () => { describe('showCommentForm', () => {
it('should call mutation to show comment form', (done) => { it('should call mutation to show comment form', () => {
const payload = { lineCode: 'lineCode', fileHash: 'hash' }; const payload = { lineCode: 'lineCode', fileHash: 'hash' };
testAction( return testAction(
showCommentForm, diffActions.showCommentForm,
payload, payload,
{}, {},
[{ type: types.TOGGLE_LINE_HAS_FORM, payload: { ...payload, hasForm: true } }], [{ type: types.TOGGLE_LINE_HAS_FORM, payload: { ...payload, hasForm: true } }],
[], [],
done,
); );
}); });
}); });
describe('cancelCommentForm', () => { describe('cancelCommentForm', () => {
it('should call mutation to cancel comment form', (done) => { it('should call mutation to cancel comment form', () => {
const payload = { lineCode: 'lineCode', fileHash: 'hash' }; const payload = { lineCode: 'lineCode', fileHash: 'hash' };
testAction( return testAction(
cancelCommentForm, diffActions.cancelCommentForm,
payload, payload,
{}, {},
[{ type: types.TOGGLE_LINE_HAS_FORM, payload: { ...payload, hasForm: false } }], [{ type: types.TOGGLE_LINE_HAS_FORM, payload: { ...payload, hasForm: false } }],
[], [],
done,
); );
}); });
}); });
describe('loadMoreLines', () => { describe('loadMoreLines', () => {
it('should call mutation to show comment form', (done) => { it('should call mutation to show comment form', () => {
const endpoint = '/diffs/load/more/lines'; const endpoint = '/diffs/load/more/lines';
const params = { since: 6, to: 26 }; const params = { since: 6, to: 26 };
const lineNumbers = { oldLineNumber: 3, newLineNumber: 5 }; const lineNumbers = { oldLineNumber: 3, newLineNumber: 5 };
...@@ -606,12 +535,11 @@ describe('DiffsStoreActions', () => { ...@@ -606,12 +535,11 @@ describe('DiffsStoreActions', () => {
const isExpandDown = false; const isExpandDown = false;
const nextLineNumbers = {}; const nextLineNumbers = {};
const options = { endpoint, params, lineNumbers, fileHash, isExpandDown, nextLineNumbers }; const options = { endpoint, params, lineNumbers, fileHash, isExpandDown, nextLineNumbers };
const mock = new MockAdapter(axios);
const contextLines = { contextLines: [{ lineCode: 6 }] }; const contextLines = { contextLines: [{ lineCode: 6 }] };
mock.onGet(endpoint).reply(200, contextLines); mock.onGet(endpoint).reply(200, contextLines);
testAction( return testAction(
loadMoreLines, diffActions.loadMoreLines,
options, options,
{}, {},
[ [
...@@ -621,31 +549,23 @@ describe('DiffsStoreActions', () => { ...@@ -621,31 +549,23 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
() => {
mock.restore();
done();
},
); );
}); });
}); });
describe('loadCollapsedDiff', () => { describe('loadCollapsedDiff', () => {
const state = { showWhitespace: true }; const state = { showWhitespace: true };
it('should fetch data and call mutation with response and the give parameter', (done) => { it('should fetch data and call mutation with response and the give parameter', () => {
const file = { hash: 123, load_collapsed_diff_url: '/load/collapsed/diff/url' }; const file = { hash: 123, load_collapsed_diff_url: '/load/collapsed/diff/url' };
const data = { hash: 123, parallelDiffLines: [{ lineCode: 1 }] }; const data = { hash: 123, parallelDiffLines: [{ lineCode: 1 }] };
const mock = new MockAdapter(axios);
const commit = jest.fn(); const commit = jest.fn();
mock.onGet(file.loadCollapsedDiffUrl).reply(200, data); mock.onGet(file.loadCollapsedDiffUrl).reply(200, data);
loadCollapsedDiff({ commit, getters: { commitId: null }, state }, file) return diffActions
.loadCollapsedDiff({ commit, getters: { commitId: null }, state }, file)
.then(() => { .then(() => {
expect(commit).toHaveBeenCalledWith(types.ADD_COLLAPSED_DIFFS, { file, data }); expect(commit).toHaveBeenCalledWith(types.ADD_COLLAPSED_DIFFS, { file, data });
});
mock.restore();
done();
})
.catch(done.fail);
}); });
it('should fetch data without commit ID', () => { it('should fetch data without commit ID', () => {
...@@ -656,7 +576,7 @@ describe('DiffsStoreActions', () => { ...@@ -656,7 +576,7 @@ describe('DiffsStoreActions', () => {
jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve({ data: {} })); jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve({ data: {} }));
loadCollapsedDiff({ commit() {}, getters, state }, file); diffActions.loadCollapsedDiff({ commit() {}, getters, state }, file);
expect(axios.get).toHaveBeenCalledWith(file.load_collapsed_diff_url, { expect(axios.get).toHaveBeenCalledWith(file.load_collapsed_diff_url, {
params: { commit_id: null, w: '0' }, params: { commit_id: null, w: '0' },
...@@ -671,7 +591,7 @@ describe('DiffsStoreActions', () => { ...@@ -671,7 +591,7 @@ describe('DiffsStoreActions', () => {
jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve({ data: {} })); jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve({ data: {} }));
loadCollapsedDiff({ commit() {}, getters, state }, file); diffActions.loadCollapsedDiff({ commit() {}, getters, state }, file);
expect(axios.get).toHaveBeenCalledWith(file.load_collapsed_diff_url, { expect(axios.get).toHaveBeenCalledWith(file.load_collapsed_diff_url, {
params: { commit_id: '123', w: '0' }, params: { commit_id: '123', w: '0' },
...@@ -689,7 +609,7 @@ describe('DiffsStoreActions', () => { ...@@ -689,7 +609,7 @@ describe('DiffsStoreActions', () => {
const dispatch = jest.fn(); const dispatch = jest.fn();
toggleFileDiscussions({ getters, dispatch }); diffActions.toggleFileDiscussions({ getters, dispatch });
expect(dispatch).toHaveBeenCalledWith( expect(dispatch).toHaveBeenCalledWith(
'collapseDiscussion', 'collapseDiscussion',
...@@ -707,7 +627,7 @@ describe('DiffsStoreActions', () => { ...@@ -707,7 +627,7 @@ describe('DiffsStoreActions', () => {
const dispatch = jest.fn(); const dispatch = jest.fn();
toggleFileDiscussions({ getters, dispatch }); diffActions.toggleFileDiscussions({ getters, dispatch });
expect(dispatch).toHaveBeenCalledWith( expect(dispatch).toHaveBeenCalledWith(
'expandDiscussion', 'expandDiscussion',
...@@ -725,7 +645,7 @@ describe('DiffsStoreActions', () => { ...@@ -725,7 +645,7 @@ describe('DiffsStoreActions', () => {
const dispatch = jest.fn(); const dispatch = jest.fn();
toggleFileDiscussions({ getters, dispatch }); diffActions.toggleFileDiscussions({ getters, dispatch });
expect(dispatch).toHaveBeenCalledWith( expect(dispatch).toHaveBeenCalledWith(
'expandDiscussion', 'expandDiscussion',
...@@ -743,7 +663,7 @@ describe('DiffsStoreActions', () => { ...@@ -743,7 +663,7 @@ describe('DiffsStoreActions', () => {
it('should not call handleLocationHash when there is not hash', () => { it('should not call handleLocationHash when there is not hash', () => {
window.location.hash = ''; window.location.hash = '';
scrollToLineIfNeededInline({}, lineMock); diffActions.scrollToLineIfNeededInline({}, lineMock);
expect(commonUtils.handleLocationHash).not.toHaveBeenCalled(); expect(commonUtils.handleLocationHash).not.toHaveBeenCalled();
}); });
...@@ -751,7 +671,7 @@ describe('DiffsStoreActions', () => { ...@@ -751,7 +671,7 @@ describe('DiffsStoreActions', () => {
it('should not call handleLocationHash when the hash does not match any line', () => { it('should not call handleLocationHash when the hash does not match any line', () => {
window.location.hash = 'XYZ_456'; window.location.hash = 'XYZ_456';
scrollToLineIfNeededInline({}, lineMock); diffActions.scrollToLineIfNeededInline({}, lineMock);
expect(commonUtils.handleLocationHash).not.toHaveBeenCalled(); expect(commonUtils.handleLocationHash).not.toHaveBeenCalled();
}); });
...@@ -759,14 +679,14 @@ describe('DiffsStoreActions', () => { ...@@ -759,14 +679,14 @@ describe('DiffsStoreActions', () => {
it('should call handleLocationHash only when the hash matches a line', () => { it('should call handleLocationHash only when the hash matches a line', () => {
window.location.hash = 'ABC_123'; window.location.hash = 'ABC_123';
scrollToLineIfNeededInline( diffActions.scrollToLineIfNeededInline(
{}, {},
{ {
lineCode: 'ABC_456', lineCode: 'ABC_456',
}, },
); );
scrollToLineIfNeededInline({}, lineMock); diffActions.scrollToLineIfNeededInline({}, lineMock);
scrollToLineIfNeededInline( diffActions.scrollToLineIfNeededInline(
{}, {},
{ {
lineCode: 'XYZ_456', lineCode: 'XYZ_456',
...@@ -789,7 +709,7 @@ describe('DiffsStoreActions', () => { ...@@ -789,7 +709,7 @@ describe('DiffsStoreActions', () => {
it('should not call handleLocationHash when there is not hash', () => { it('should not call handleLocationHash when there is not hash', () => {
window.location.hash = ''; window.location.hash = '';
scrollToLineIfNeededParallel({}, lineMock); diffActions.scrollToLineIfNeededParallel({}, lineMock);
expect(commonUtils.handleLocationHash).not.toHaveBeenCalled(); expect(commonUtils.handleLocationHash).not.toHaveBeenCalled();
}); });
...@@ -797,7 +717,7 @@ describe('DiffsStoreActions', () => { ...@@ -797,7 +717,7 @@ describe('DiffsStoreActions', () => {
it('should not call handleLocationHash when the hash does not match any line', () => { it('should not call handleLocationHash when the hash does not match any line', () => {
window.location.hash = 'XYZ_456'; window.location.hash = 'XYZ_456';
scrollToLineIfNeededParallel({}, lineMock); diffActions.scrollToLineIfNeededParallel({}, lineMock);
expect(commonUtils.handleLocationHash).not.toHaveBeenCalled(); expect(commonUtils.handleLocationHash).not.toHaveBeenCalled();
}); });
...@@ -805,7 +725,7 @@ describe('DiffsStoreActions', () => { ...@@ -805,7 +725,7 @@ describe('DiffsStoreActions', () => {
it('should call handleLocationHash only when the hash matches a line', () => { it('should call handleLocationHash only when the hash matches a line', () => {
window.location.hash = 'ABC_123'; window.location.hash = 'ABC_123';
scrollToLineIfNeededParallel( diffActions.scrollToLineIfNeededParallel(
{}, {},
{ {
left: null, left: null,
...@@ -814,8 +734,8 @@ describe('DiffsStoreActions', () => { ...@@ -814,8 +734,8 @@ describe('DiffsStoreActions', () => {
}, },
}, },
); );
scrollToLineIfNeededParallel({}, lineMock); diffActions.scrollToLineIfNeededParallel({}, lineMock);
scrollToLineIfNeededParallel( diffActions.scrollToLineIfNeededParallel(
{}, {},
{ {
left: null, left: null,
...@@ -831,7 +751,7 @@ describe('DiffsStoreActions', () => { ...@@ -831,7 +751,7 @@ describe('DiffsStoreActions', () => {
}); });
describe('saveDiffDiscussion', () => { describe('saveDiffDiscussion', () => {
it('dispatches actions', (done) => { it('dispatches actions', () => {
const commitId = 'something'; const commitId = 'something';
const formData = { const formData = {
diffFile: { ...mockDiffFile }, diffFile: { ...mockDiffFile },
...@@ -856,8 +776,7 @@ describe('DiffsStoreActions', () => { ...@@ -856,8 +776,7 @@ describe('DiffsStoreActions', () => {
} }
}); });
saveDiffDiscussion({ state, dispatch }, { note, formData }) return diffActions.saveDiffDiscussion({ state, dispatch }, { note, formData }).then(() => {
.then(() => {
expect(dispatch).toHaveBeenCalledTimes(5); expect(dispatch).toHaveBeenCalledTimes(5);
expect(dispatch).toHaveBeenNthCalledWith(1, 'saveNote', expect.any(Object), { expect(dispatch).toHaveBeenNthCalledWith(1, 'saveNote', expect.any(Object), {
root: true, root: true,
...@@ -868,21 +787,18 @@ describe('DiffsStoreActions', () => { ...@@ -868,21 +787,18 @@ describe('DiffsStoreActions', () => {
expect(dispatch).toHaveBeenNthCalledWith(2, 'updateDiscussion', 'test', { root: true }); expect(dispatch).toHaveBeenNthCalledWith(2, 'updateDiscussion', 'test', { root: true });
expect(dispatch).toHaveBeenNthCalledWith(3, 'assignDiscussionsToDiff', ['discussion']); expect(dispatch).toHaveBeenNthCalledWith(3, 'assignDiscussionsToDiff', ['discussion']);
}) });
.then(done)
.catch(done.fail);
}); });
}); });
describe('toggleTreeOpen', () => { describe('toggleTreeOpen', () => {
it('commits TOGGLE_FOLDER_OPEN', (done) => { it('commits TOGGLE_FOLDER_OPEN', () => {
testAction( return testAction(
toggleTreeOpen, diffActions.toggleTreeOpen,
'path', 'path',
{}, {},
[{ type: types.TOGGLE_FOLDER_OPEN, payload: 'path' }], [{ type: types.TOGGLE_FOLDER_OPEN, payload: 'path' }],
[], [],
done,
); );
}); });
}); });
...@@ -904,7 +820,7 @@ describe('DiffsStoreActions', () => { ...@@ -904,7 +820,7 @@ describe('DiffsStoreActions', () => {
}, },
}; };
scrollToFile({ state, commit, getters }, { path: 'path' }); diffActions.scrollToFile({ state, commit, getters }, { path: 'path' });
expect(document.location.hash).toBe('#test'); expect(document.location.hash).toBe('#test');
}); });
...@@ -918,28 +834,27 @@ describe('DiffsStoreActions', () => { ...@@ -918,28 +834,27 @@ describe('DiffsStoreActions', () => {
}, },
}; };
scrollToFile({ state, commit, getters }, { path: 'path' }); diffActions.scrollToFile({ state, commit, getters }, { path: 'path' });
expect(commit).toHaveBeenCalledWith(types.SET_CURRENT_DIFF_FILE, 'test'); expect(commit).toHaveBeenCalledWith(types.SET_CURRENT_DIFF_FILE, 'test');
}); });
}); });
describe('setShowTreeList', () => { describe('setShowTreeList', () => {
it('commits toggle', (done) => { it('commits toggle', () => {
testAction( return testAction(
setShowTreeList, diffActions.setShowTreeList,
{ showTreeList: true }, { showTreeList: true },
{}, {},
[{ type: types.SET_SHOW_TREE_LIST, payload: true }], [{ type: types.SET_SHOW_TREE_LIST, payload: true }],
[], [],
done,
); );
}); });
it('updates localStorage', () => { it('updates localStorage', () => {
jest.spyOn(localStorage, 'setItem').mockImplementation(() => {}); jest.spyOn(localStorage, 'setItem').mockImplementation(() => {});
setShowTreeList({ commit() {} }, { showTreeList: true }); diffActions.setShowTreeList({ commit() {} }, { showTreeList: true });
expect(localStorage.setItem).toHaveBeenCalledWith('mr_tree_show', true); expect(localStorage.setItem).toHaveBeenCalledWith('mr_tree_show', true);
}); });
...@@ -947,7 +862,7 @@ describe('DiffsStoreActions', () => { ...@@ -947,7 +862,7 @@ describe('DiffsStoreActions', () => {
it('does not update localStorage', () => { it('does not update localStorage', () => {
jest.spyOn(localStorage, 'setItem').mockImplementation(() => {}); jest.spyOn(localStorage, 'setItem').mockImplementation(() => {});
setShowTreeList({ commit() {} }, { showTreeList: true, saving: false }); diffActions.setShowTreeList({ commit() {} }, { showTreeList: true, saving: false });
expect(localStorage.setItem).not.toHaveBeenCalled(); expect(localStorage.setItem).not.toHaveBeenCalled();
}); });
...@@ -994,7 +909,7 @@ describe('DiffsStoreActions', () => { ...@@ -994,7 +909,7 @@ describe('DiffsStoreActions', () => {
it('renders and expands file for the given discussion id', () => { it('renders and expands file for the given discussion id', () => {
const localState = state({ collapsed: true, renderIt: false }); const localState = state({ collapsed: true, renderIt: false });
renderFileForDiscussionId({ rootState, state: localState, commit }, '123'); diffActions.renderFileForDiscussionId({ rootState, state: localState, commit }, '123');
expect(commit).toHaveBeenCalledWith('RENDER_FILE', localState.diffFiles[0]); expect(commit).toHaveBeenCalledWith('RENDER_FILE', localState.diffFiles[0]);
expect($emit).toHaveBeenCalledTimes(1); expect($emit).toHaveBeenCalledTimes(1);
...@@ -1004,7 +919,7 @@ describe('DiffsStoreActions', () => { ...@@ -1004,7 +919,7 @@ describe('DiffsStoreActions', () => {
it('jumps to discussion on already rendered and expanded file', () => { it('jumps to discussion on already rendered and expanded file', () => {
const localState = state({ collapsed: false, renderIt: true }); const localState = state({ collapsed: false, renderIt: true });
renderFileForDiscussionId({ rootState, state: localState, commit }, '123'); diffActions.renderFileForDiscussionId({ rootState, state: localState, commit }, '123');
expect(commit).not.toHaveBeenCalled(); expect(commit).not.toHaveBeenCalled();
expect($emit).toHaveBeenCalledTimes(1); expect($emit).toHaveBeenCalledTimes(1);
...@@ -1013,19 +928,18 @@ describe('DiffsStoreActions', () => { ...@@ -1013,19 +928,18 @@ describe('DiffsStoreActions', () => {
}); });
describe('setRenderTreeList', () => { describe('setRenderTreeList', () => {
it('commits SET_RENDER_TREE_LIST', (done) => { it('commits SET_RENDER_TREE_LIST', () => {
testAction( return testAction(
setRenderTreeList, diffActions.setRenderTreeList,
{ renderTreeList: true }, { renderTreeList: true },
{}, {},
[{ type: types.SET_RENDER_TREE_LIST, payload: true }], [{ type: types.SET_RENDER_TREE_LIST, payload: true }],
[], [],
done,
); );
}); });
it('sets localStorage', () => { it('sets localStorage', () => {
setRenderTreeList({ commit() {} }, { renderTreeList: true }); diffActions.setRenderTreeList({ commit() {} }, { renderTreeList: true });
expect(localStorage.setItem).toHaveBeenCalledWith('mr_diff_tree_list', true); expect(localStorage.setItem).toHaveBeenCalledWith('mr_diff_tree_list', true);
}); });
...@@ -1034,11 +948,9 @@ describe('DiffsStoreActions', () => { ...@@ -1034,11 +948,9 @@ describe('DiffsStoreActions', () => {
describe('setShowWhitespace', () => { describe('setShowWhitespace', () => {
const endpointUpdateUser = 'user/prefs'; const endpointUpdateUser = 'user/prefs';
let putSpy; let putSpy;
let mock;
let gon; let gon;
beforeEach(() => { beforeEach(() => {
mock = new MockAdapter(axios);
putSpy = jest.spyOn(axios, 'put'); putSpy = jest.spyOn(axios, 'put');
gon = window.gon; gon = window.gon;
...@@ -1047,25 +959,23 @@ describe('DiffsStoreActions', () => { ...@@ -1047,25 +959,23 @@ describe('DiffsStoreActions', () => {
}); });
afterEach(() => { afterEach(() => {
mock.restore();
window.gon = gon; window.gon = gon;
}); });
it('commits SET_SHOW_WHITESPACE', (done) => { it('commits SET_SHOW_WHITESPACE', () => {
testAction( return testAction(
setShowWhitespace, diffActions.setShowWhitespace,
{ showWhitespace: true, updateDatabase: false }, { showWhitespace: true, updateDatabase: false },
{}, {},
[{ type: types.SET_SHOW_WHITESPACE, payload: true }], [{ type: types.SET_SHOW_WHITESPACE, payload: true }],
[], [],
done,
); );
}); });
it('saves to the database when the user is logged in', async () => { it('saves to the database when the user is logged in', async () => {
window.gon = { current_user_id: 12345 }; window.gon = { current_user_id: 12345 };
await setShowWhitespace( await diffActions.setShowWhitespace(
{ state: { endpointUpdateUser }, commit() {} }, { state: { endpointUpdateUser }, commit() {} },
{ showWhitespace: true, updateDatabase: true }, { showWhitespace: true, updateDatabase: true },
); );
...@@ -1076,7 +986,7 @@ describe('DiffsStoreActions', () => { ...@@ -1076,7 +986,7 @@ describe('DiffsStoreActions', () => {
it('does not try to save to the API if the user is not logged in', async () => { it('does not try to save to the API if the user is not logged in', async () => {
window.gon = {}; window.gon = {};
await setShowWhitespace( await diffActions.setShowWhitespace(
{ state: { endpointUpdateUser }, commit() {} }, { state: { endpointUpdateUser }, commit() {} },
{ showWhitespace: true, updateDatabase: true }, { showWhitespace: true, updateDatabase: true },
); );
...@@ -1085,7 +995,7 @@ describe('DiffsStoreActions', () => { ...@@ -1085,7 +995,7 @@ describe('DiffsStoreActions', () => {
}); });
it('emits eventHub event', async () => { it('emits eventHub event', async () => {
await setShowWhitespace( await diffActions.setShowWhitespace(
{ state: {}, commit() {} }, { state: {}, commit() {} },
{ showWhitespace: true, updateDatabase: false }, { showWhitespace: true, updateDatabase: false },
); );
...@@ -1095,53 +1005,47 @@ describe('DiffsStoreActions', () => { ...@@ -1095,53 +1005,47 @@ describe('DiffsStoreActions', () => {
}); });
describe('setRenderIt', () => { describe('setRenderIt', () => {
it('commits RENDER_FILE', (done) => { it('commits RENDER_FILE', () => {
testAction(setRenderIt, 'file', {}, [{ type: types.RENDER_FILE, payload: 'file' }], [], done); return testAction(
diffActions.setRenderIt,
'file',
{},
[{ type: types.RENDER_FILE, payload: 'file' }],
[],
);
}); });
}); });
describe('receiveFullDiffError', () => { describe('receiveFullDiffError', () => {
it('updates state with the file that did not load', (done) => { it('updates state with the file that did not load', () => {
testAction( return testAction(
receiveFullDiffError, diffActions.receiveFullDiffError,
'file', 'file',
{}, {},
[{ type: types.RECEIVE_FULL_DIFF_ERROR, payload: 'file' }], [{ type: types.RECEIVE_FULL_DIFF_ERROR, payload: 'file' }],
[], [],
done,
); );
}); });
}); });
describe('fetchFullDiff', () => { describe('fetchFullDiff', () => {
let mock;
beforeEach(() => {
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
});
describe('success', () => { describe('success', () => {
beforeEach(() => { beforeEach(() => {
mock.onGet(`${TEST_HOST}/context`).replyOnce(200, ['test']); mock.onGet(`${TEST_HOST}/context`).replyOnce(200, ['test']);
}); });
it('commits the success and dispatches an action to expand the new lines', (done) => { it('commits the success and dispatches an action to expand the new lines', () => {
const file = { const file = {
context_lines_path: `${TEST_HOST}/context`, context_lines_path: `${TEST_HOST}/context`,
file_path: 'test', file_path: 'test',
file_hash: 'test', file_hash: 'test',
}; };
testAction( return testAction(
fetchFullDiff, diffActions.fetchFullDiff,
file, file,
null, null,
[{ type: types.RECEIVE_FULL_DIFF_SUCCESS, payload: { filePath: 'test' } }], [{ type: types.RECEIVE_FULL_DIFF_SUCCESS, payload: { filePath: 'test' } }],
[{ type: 'setExpandedDiffLines', payload: { file, data: ['test'] } }], [{ type: 'setExpandedDiffLines', payload: { file, data: ['test'] } }],
done,
); );
}); });
}); });
...@@ -1151,14 +1055,13 @@ describe('DiffsStoreActions', () => { ...@@ -1151,14 +1055,13 @@ describe('DiffsStoreActions', () => {
mock.onGet(`${TEST_HOST}/context`).replyOnce(500); mock.onGet(`${TEST_HOST}/context`).replyOnce(500);
}); });
it('dispatches receiveFullDiffError', (done) => { it('dispatches receiveFullDiffError', () => {
testAction( return testAction(
fetchFullDiff, diffActions.fetchFullDiff,
{ context_lines_path: `${TEST_HOST}/context`, file_path: 'test', file_hash: 'test' }, { context_lines_path: `${TEST_HOST}/context`, file_path: 'test', file_hash: 'test' },
null, null,
[], [],
[{ type: 'receiveFullDiffError', payload: 'test' }], [{ type: 'receiveFullDiffError', payload: 'test' }],
done,
); );
}); });
}); });
...@@ -1173,14 +1076,13 @@ describe('DiffsStoreActions', () => { ...@@ -1173,14 +1076,13 @@ describe('DiffsStoreActions', () => {
}; };
}); });
it('dispatches fetchFullDiff when file is not expanded', (done) => { it('dispatches fetchFullDiff when file is not expanded', () => {
testAction( return testAction(
toggleFullDiff, diffActions.toggleFullDiff,
'test', 'test',
state, state,
[{ type: types.REQUEST_FULL_DIFF, payload: 'test' }], [{ type: types.REQUEST_FULL_DIFF, payload: 'test' }],
[{ type: 'fetchFullDiff', payload: state.diffFiles[0] }], [{ type: 'fetchFullDiff', payload: state.diffFiles[0] }],
done,
); );
}); });
}); });
...@@ -1202,16 +1104,13 @@ describe('DiffsStoreActions', () => { ...@@ -1202,16 +1104,13 @@ describe('DiffsStoreActions', () => {
}; };
const testData = [{ rich_text: 'test' }, { rich_text: 'file2' }]; const testData = [{ rich_text: 'test' }, { rich_text: 'file2' }];
let renamedFile; let renamedFile;
let mock;
beforeEach(() => { beforeEach(() => {
mock = new MockAdapter(axios);
jest.spyOn(utils, 'prepareLineForRenamedFile').mockImplementation(() => preparedLine); jest.spyOn(utils, 'prepareLineForRenamedFile').mockImplementation(() => preparedLine);
}); });
afterEach(() => { afterEach(() => {
renamedFile = null; renamedFile = null;
mock.restore();
}); });
describe('success', () => { describe('success', () => {
...@@ -1228,7 +1127,7 @@ describe('DiffsStoreActions', () => { ...@@ -1228,7 +1127,7 @@ describe('DiffsStoreActions', () => {
'performs the correct mutations and starts a render queue for view type $diffViewType', 'performs the correct mutations and starts a render queue for view type $diffViewType',
({ diffViewType }) => { ({ diffViewType }) => {
return testAction( return testAction(
switchToFullDiffFromRenamedFile, diffActions.switchToFullDiffFromRenamedFile,
{ diffFile: renamedFile }, { diffFile: renamedFile },
{ diffViewType }, { diffViewType },
[ [
...@@ -1249,9 +1148,9 @@ describe('DiffsStoreActions', () => { ...@@ -1249,9 +1148,9 @@ describe('DiffsStoreActions', () => {
}); });
describe('setFileUserCollapsed', () => { describe('setFileUserCollapsed', () => {
it('commits SET_FILE_COLLAPSED', (done) => { it('commits SET_FILE_COLLAPSED', () => {
testAction( return testAction(
setFileCollapsedByUser, diffActions.setFileCollapsedByUser,
{ filePath: 'test', collapsed: true }, { filePath: 'test', collapsed: true },
null, null,
[ [
...@@ -1261,7 +1160,6 @@ describe('DiffsStoreActions', () => { ...@@ -1261,7 +1160,6 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -1273,11 +1171,11 @@ describe('DiffsStoreActions', () => { ...@@ -1273,11 +1171,11 @@ describe('DiffsStoreActions', () => {
}); });
}); });
it('commits SET_CURRENT_VIEW_DIFF_FILE_LINES when lines less than MAX_RENDERING_DIFF_LINES', (done) => { it('commits SET_CURRENT_VIEW_DIFF_FILE_LINES when lines less than MAX_RENDERING_DIFF_LINES', () => {
utils.convertExpandLines.mockImplementation(() => ['test']); utils.convertExpandLines.mockImplementation(() => ['test']);
testAction( return testAction(
setExpandedDiffLines, diffActions.setExpandedDiffLines,
{ file: { file_path: 'path' }, data: [] }, { file: { file_path: 'path' }, data: [] },
{ diffViewType: 'inline' }, { diffViewType: 'inline' },
[ [
...@@ -1287,16 +1185,15 @@ describe('DiffsStoreActions', () => { ...@@ -1287,16 +1185,15 @@ describe('DiffsStoreActions', () => {
}, },
], ],
[], [],
done,
); );
}); });
it('commits ADD_CURRENT_VIEW_DIFF_FILE_LINES when lines more than MAX_RENDERING_DIFF_LINES', (done) => { it('commits ADD_CURRENT_VIEW_DIFF_FILE_LINES when lines more than MAX_RENDERING_DIFF_LINES', () => {
const lines = new Array(501).fill().map((_, i) => `line-${i}`); const lines = new Array(501).fill().map((_, i) => `line-${i}`);
utils.convertExpandLines.mockReturnValue(lines); utils.convertExpandLines.mockReturnValue(lines);
testAction( return testAction(
setExpandedDiffLines, diffActions.setExpandedDiffLines,
{ file: { file_path: 'path' }, data: [] }, { file: { file_path: 'path' }, data: [] },
{ diffViewType: 'inline' }, { diffViewType: 'inline' },
[ [
...@@ -1312,41 +1209,34 @@ describe('DiffsStoreActions', () => { ...@@ -1312,41 +1209,34 @@ describe('DiffsStoreActions', () => {
{ type: 'TOGGLE_DIFF_FILE_RENDERING_MORE', payload: 'path' }, { type: 'TOGGLE_DIFF_FILE_RENDERING_MORE', payload: 'path' },
], ],
[], [],
done,
); );
}); });
}); });
describe('setSuggestPopoverDismissed', () => { describe('setSuggestPopoverDismissed', () => {
it('commits SET_SHOW_SUGGEST_POPOVER', (done) => { it('commits SET_SHOW_SUGGEST_POPOVER', async () => {
const state = { dismissEndpoint: `${TEST_HOST}/-/user_callouts` }; const state = { dismissEndpoint: `${TEST_HOST}/-/user_callouts` };
const mock = new MockAdapter(axios);
mock.onPost(state.dismissEndpoint).reply(200, {}); mock.onPost(state.dismissEndpoint).reply(200, {});
jest.spyOn(axios, 'post'); jest.spyOn(axios, 'post');
testAction( await testAction(
setSuggestPopoverDismissed, diffActions.setSuggestPopoverDismissed,
null, null,
state, state,
[{ type: types.SET_SHOW_SUGGEST_POPOVER }], [{ type: types.SET_SHOW_SUGGEST_POPOVER }],
[], [],
() => { );
expect(axios.post).toHaveBeenCalledWith(state.dismissEndpoint, { expect(axios.post).toHaveBeenCalledWith(state.dismissEndpoint, {
feature_name: 'suggest_popover_dismissed', feature_name: 'suggest_popover_dismissed',
}); });
mock.restore();
done();
},
);
}); });
}); });
describe('changeCurrentCommit', () => { describe('changeCurrentCommit', () => {
it('commits the new commit information and re-requests the diff metadata for the commit', () => { it('commits the new commit information and re-requests the diff metadata for the commit', () => {
return testAction( return testAction(
changeCurrentCommit, diffActions.changeCurrentCommit,
{ commitId: 'NEW' }, { commitId: 'NEW' },
{ {
commit: { commit: {
...@@ -1384,7 +1274,7 @@ describe('DiffsStoreActions', () => { ...@@ -1384,7 +1274,7 @@ describe('DiffsStoreActions', () => {
({ commitId, commit, msg }) => { ({ commitId, commit, msg }) => {
const err = new Error(msg); const err = new Error(msg);
const actionReturn = testAction( const actionReturn = testAction(
changeCurrentCommit, diffActions.changeCurrentCommit,
{ commitId }, { commitId },
{ {
endpoint: 'URL/OLD', endpoint: 'URL/OLD',
...@@ -1410,7 +1300,7 @@ describe('DiffsStoreActions', () => { ...@@ -1410,7 +1300,7 @@ describe('DiffsStoreActions', () => {
'for the direction "$direction", dispatches the action to move to the SHA "$expected"', 'for the direction "$direction", dispatches the action to move to the SHA "$expected"',
({ direction, expected, currentCommit }) => { ({ direction, expected, currentCommit }) => {
return testAction( return testAction(
moveToNeighboringCommit, diffActions.moveToNeighboringCommit,
{ direction }, { direction },
{ commit: currentCommit }, { commit: currentCommit },
[], [],
...@@ -1431,7 +1321,7 @@ describe('DiffsStoreActions', () => { ...@@ -1431,7 +1321,7 @@ describe('DiffsStoreActions', () => {
'given `{ "isloading": $diffsAreLoading, "commit": $currentCommit }` in state, no actions are dispatched', 'given `{ "isloading": $diffsAreLoading, "commit": $currentCommit }` in state, no actions are dispatched',
({ direction, diffsAreLoading, currentCommit }) => { ({ direction, diffsAreLoading, currentCommit }) => {
return testAction( return testAction(
moveToNeighboringCommit, diffActions.moveToNeighboringCommit,
{ direction }, { direction },
{ commit: currentCommit, isLoading: diffsAreLoading }, { commit: currentCommit, isLoading: diffsAreLoading },
[], [],
...@@ -1450,7 +1340,7 @@ describe('DiffsStoreActions', () => { ...@@ -1450,7 +1340,7 @@ describe('DiffsStoreActions', () => {
notesById: { 1: { discussion_id: '2' } }, notesById: { 1: { discussion_id: '2' } },
}; };
setCurrentDiffFileIdFromNote({ commit, state, rootGetters }, '1'); diffActions.setCurrentDiffFileIdFromNote({ commit, state, rootGetters }, '1');
expect(commit).toHaveBeenCalledWith(types.SET_CURRENT_DIFF_FILE, '123'); expect(commit).toHaveBeenCalledWith(types.SET_CURRENT_DIFF_FILE, '123');
}); });
...@@ -1463,7 +1353,7 @@ describe('DiffsStoreActions', () => { ...@@ -1463,7 +1353,7 @@ describe('DiffsStoreActions', () => {
notesById: { 1: { discussion_id: '2' } }, notesById: { 1: { discussion_id: '2' } },
}; };
setCurrentDiffFileIdFromNote({ commit, state, rootGetters }, '1'); diffActions.setCurrentDiffFileIdFromNote({ commit, state, rootGetters }, '1');
expect(commit).not.toHaveBeenCalled(); expect(commit).not.toHaveBeenCalled();
}); });
...@@ -1476,21 +1366,20 @@ describe('DiffsStoreActions', () => { ...@@ -1476,21 +1366,20 @@ describe('DiffsStoreActions', () => {
notesById: { 1: { discussion_id: '2' } }, notesById: { 1: { discussion_id: '2' } },
}; };
setCurrentDiffFileIdFromNote({ commit, state, rootGetters }, '1'); diffActions.setCurrentDiffFileIdFromNote({ commit, state, rootGetters }, '1');
expect(commit).not.toHaveBeenCalled(); expect(commit).not.toHaveBeenCalled();
}); });
}); });
describe('navigateToDiffFileIndex', () => { describe('navigateToDiffFileIndex', () => {
it('commits SET_CURRENT_DIFF_FILE', (done) => { it('commits SET_CURRENT_DIFF_FILE', () => {
testAction( return testAction(
navigateToDiffFileIndex, diffActions.navigateToDiffFileIndex,
0, 0,
{ diffFiles: [{ file_hash: '123' }] }, { diffFiles: [{ file_hash: '123' }] },
[{ type: types.SET_CURRENT_DIFF_FILE, payload: '123' }], [{ type: types.SET_CURRENT_DIFF_FILE, payload: '123' }],
[], [],
done,
); );
}); });
}); });
...@@ -1498,19 +1387,13 @@ describe('DiffsStoreActions', () => { ...@@ -1498,19 +1387,13 @@ describe('DiffsStoreActions', () => {
describe('setFileByFile', () => { describe('setFileByFile', () => {
const updateUserEndpoint = 'user/prefs'; const updateUserEndpoint = 'user/prefs';
let putSpy; let putSpy;
let mock;
beforeEach(() => { beforeEach(() => {
mock = new MockAdapter(axios);
putSpy = jest.spyOn(axios, 'put'); putSpy = jest.spyOn(axios, 'put');
mock.onPut(updateUserEndpoint).reply(200, {}); mock.onPut(updateUserEndpoint).reply(200, {});
}); });
afterEach(() => {
mock.restore();
});
it.each` it.each`
value value
${true} ${true}
...@@ -1519,7 +1402,7 @@ describe('DiffsStoreActions', () => { ...@@ -1519,7 +1402,7 @@ describe('DiffsStoreActions', () => {
'commits SET_FILE_BY_FILE and persists the File-by-File user preference with the new value $value', 'commits SET_FILE_BY_FILE and persists the File-by-File user preference with the new value $value',
async ({ value }) => { async ({ value }) => {
await testAction( await testAction(
setFileByFile, diffActions.setFileByFile,
{ fileByFile: value }, { fileByFile: value },
{ {
viewDiffsFileByFile: null, viewDiffsFileByFile: null,
...@@ -1551,7 +1434,7 @@ describe('DiffsStoreActions', () => { ...@@ -1551,7 +1434,7 @@ describe('DiffsStoreActions', () => {
const commitSpy = jest.fn(); const commitSpy = jest.fn();
const getterSpy = jest.fn().mockReturnValue([]); const getterSpy = jest.fn().mockReturnValue([]);
reviewFile( diffActions.reviewFile(
{ {
commit: commitSpy, commit: commitSpy,
getters: { getters: {
......
...@@ -23,9 +23,9 @@ describe('Deploy Board', () => { ...@@ -23,9 +23,9 @@ describe('Deploy Board', () => {
}); });
describe('with valid data', () => { describe('with valid data', () => {
beforeEach((done) => { beforeEach(() => {
wrapper = createComponent(); wrapper = createComponent();
nextTick(done); return nextTick();
}); });
it('should render percentage with completion value provided', () => { it('should render percentage with completion value provided', () => {
...@@ -127,14 +127,14 @@ describe('Deploy Board', () => { ...@@ -127,14 +127,14 @@ describe('Deploy Board', () => {
}); });
describe('with empty state', () => { describe('with empty state', () => {
beforeEach((done) => { beforeEach(() => {
wrapper = createComponent({ wrapper = createComponent({
deployBoardData: {}, deployBoardData: {},
isLoading: false, isLoading: false,
isEmpty: true, isEmpty: true,
logsPath, logsPath,
}); });
nextTick(done); return nextTick();
}); });
it('should render the empty state', () => { it('should render the empty state', () => {
...@@ -146,14 +146,14 @@ describe('Deploy Board', () => { ...@@ -146,14 +146,14 @@ describe('Deploy Board', () => {
}); });
describe('with loading state', () => { describe('with loading state', () => {
beforeEach((done) => { beforeEach(() => {
wrapper = createComponent({ wrapper = createComponent({
deployBoardData: {}, deployBoardData: {},
isLoading: true, isLoading: true,
isEmpty: false, isEmpty: false,
logsPath, logsPath,
}); });
nextTick(done); return nextTick();
}); });
it('should render loading spinner', () => { it('should render loading spinner', () => {
...@@ -163,7 +163,7 @@ describe('Deploy Board', () => { ...@@ -163,7 +163,7 @@ describe('Deploy Board', () => {
describe('has legend component', () => { describe('has legend component', () => {
let statuses = []; let statuses = [];
beforeEach((done) => { beforeEach(() => {
wrapper = createComponent({ wrapper = createComponent({
isLoading: false, isLoading: false,
isEmpty: false, isEmpty: false,
...@@ -171,7 +171,7 @@ describe('Deploy Board', () => { ...@@ -171,7 +171,7 @@ describe('Deploy Board', () => {
deployBoardData: deployBoardMockData, deployBoardData: deployBoardMockData,
}); });
({ statuses } = wrapper.vm); ({ statuses } = wrapper.vm);
nextTick(done); return nextTick();
}); });
it('with all the possible statuses', () => { it('with all the possible statuses', () => {
......
...@@ -122,7 +122,7 @@ describe('Environment table', () => { ...@@ -122,7 +122,7 @@ describe('Environment table', () => {
expect(wrapper.find('.deploy-board-icon').exists()).toBe(true); expect(wrapper.find('.deploy-board-icon').exists()).toBe(true);
}); });
it('should toggle deploy board visibility when arrow is clicked', (done) => { it('should toggle deploy board visibility when arrow is clicked', async () => {
const mockItem = { const mockItem = {
name: 'review', name: 'review',
size: 1, size: 1,
...@@ -142,7 +142,6 @@ describe('Environment table', () => { ...@@ -142,7 +142,6 @@ describe('Environment table', () => {
eventHub.$on('toggleDeployBoard', (env) => { eventHub.$on('toggleDeployBoard', (env) => {
expect(env.id).toEqual(mockItem.id); expect(env.id).toEqual(mockItem.id);
done();
}); });
factory({ factory({
...@@ -154,7 +153,7 @@ describe('Environment table', () => { ...@@ -154,7 +153,7 @@ describe('Environment table', () => {
}, },
}); });
wrapper.find('.deploy-board-icon').trigger('click'); await wrapper.find('.deploy-board-icon').trigger('click');
}); });
it('should set the environment to change and weight when a change canary weight event is recevied', async () => { it('should set the environment to change and weight when a change canary weight event is recevied', async () => {
......
...@@ -28,9 +28,9 @@ describe('Sentry common store actions', () => { ...@@ -28,9 +28,9 @@ describe('Sentry common store actions', () => {
const params = { endpoint, redirectUrl, status }; const params = { endpoint, redirectUrl, status };
describe('updateStatus', () => { describe('updateStatus', () => {
it('should handle successful status update', (done) => { it('should handle successful status update', async () => {
mock.onPut().reply(200, {}); mock.onPut().reply(200, {});
testAction( await testAction(
actions.updateStatus, actions.updateStatus,
params, params,
{}, {},
...@@ -41,20 +41,15 @@ describe('Sentry common store actions', () => { ...@@ -41,20 +41,15 @@ describe('Sentry common store actions', () => {
}, },
], ],
[], [],
() => {
done();
expect(visitUrl).toHaveBeenCalledWith(redirectUrl);
},
); );
expect(visitUrl).toHaveBeenCalledWith(redirectUrl);
}); });
it('should handle unsuccessful status update', (done) => { it('should handle unsuccessful status update', async () => {
mock.onPut().reply(400, {}); mock.onPut().reply(400, {});
testAction(actions.updateStatus, params, {}, [], [], () => { await testAction(actions.updateStatus, params, {}, [], []);
expect(visitUrl).not.toHaveBeenCalled(); expect(visitUrl).not.toHaveBeenCalled();
expect(createFlash).toHaveBeenCalledTimes(1); expect(createFlash).toHaveBeenCalledTimes(1);
done();
});
}); });
}); });
......
...@@ -28,10 +28,10 @@ describe('Sentry error details store actions', () => { ...@@ -28,10 +28,10 @@ describe('Sentry error details store actions', () => {
describe('startPollingStacktrace', () => { describe('startPollingStacktrace', () => {
const endpoint = '123/stacktrace'; const endpoint = '123/stacktrace';
it('should commit SET_ERROR with received response', (done) => { it('should commit SET_ERROR with received response', () => {
const payload = { error: [1, 2, 3] }; const payload = { error: [1, 2, 3] };
mockedAdapter.onGet().reply(200, payload); mockedAdapter.onGet().reply(200, payload);
testAction( return testAction(
actions.startPollingStacktrace, actions.startPollingStacktrace,
{ endpoint }, { endpoint },
{}, {},
...@@ -40,37 +40,29 @@ describe('Sentry error details store actions', () => { ...@@ -40,37 +40,29 @@ describe('Sentry error details store actions', () => {
{ type: types.SET_LOADING_STACKTRACE, payload: false }, { type: types.SET_LOADING_STACKTRACE, payload: false },
], ],
[], [],
() => {
done();
},
); );
}); });
it('should show flash on API error', (done) => { it('should show flash on API error', async () => {
mockedAdapter.onGet().reply(400); mockedAdapter.onGet().reply(400);
testAction( await testAction(
actions.startPollingStacktrace, actions.startPollingStacktrace,
{ endpoint }, { endpoint },
{}, {},
[{ type: types.SET_LOADING_STACKTRACE, payload: false }], [{ type: types.SET_LOADING_STACKTRACE, payload: false }],
[], [],
() => {
expect(createFlash).toHaveBeenCalledTimes(1);
done();
},
); );
expect(createFlash).toHaveBeenCalledTimes(1);
}); });
it('should not restart polling when receiving an empty 204 response', (done) => { it('should not restart polling when receiving an empty 204 response', async () => {
mockedRestart = jest.spyOn(Poll.prototype, 'restart'); mockedRestart = jest.spyOn(Poll.prototype, 'restart');
mockedAdapter.onGet().reply(204); mockedAdapter.onGet().reply(204);
testAction(actions.startPollingStacktrace, { endpoint }, {}, [], [], () => { await testAction(actions.startPollingStacktrace, { endpoint }, {}, [], []);
mockedRestart = jest.spyOn(Poll.prototype, 'restart'); mockedRestart = jest.spyOn(Poll.prototype, 'restart');
expect(mockedRestart).toHaveBeenCalledTimes(0); expect(mockedRestart).toHaveBeenCalledTimes(0);
done();
});
}); });
}); });
}); });
...@@ -20,11 +20,11 @@ describe('error tracking actions', () => { ...@@ -20,11 +20,11 @@ describe('error tracking actions', () => {
}); });
describe('startPolling', () => { describe('startPolling', () => {
it('should start polling for data', (done) => { it('should start polling for data', () => {
const payload = { errors: [{ id: 1 }, { id: 2 }] }; const payload = { errors: [{ id: 1 }, { id: 2 }] };
mock.onGet().reply(httpStatusCodes.OK, payload); mock.onGet().reply(httpStatusCodes.OK, payload);
testAction( return testAction(
actions.startPolling, actions.startPolling,
{}, {},
{}, {},
...@@ -35,16 +35,13 @@ describe('error tracking actions', () => { ...@@ -35,16 +35,13 @@ describe('error tracking actions', () => {
{ type: types.SET_LOADING, payload: false }, { type: types.SET_LOADING, payload: false },
], ],
[{ type: 'stopPolling' }], [{ type: 'stopPolling' }],
() => {
done();
},
); );
}); });
it('should show flash on API error', (done) => { it('should show flash on API error', async () => {
mock.onGet().reply(httpStatusCodes.BAD_REQUEST); mock.onGet().reply(httpStatusCodes.BAD_REQUEST);
testAction( await testAction(
actions.startPolling, actions.startPolling,
{}, {},
{}, {},
...@@ -53,11 +50,8 @@ describe('error tracking actions', () => { ...@@ -53,11 +50,8 @@ describe('error tracking actions', () => {
{ type: types.SET_LOADING, payload: false }, { type: types.SET_LOADING, payload: false },
], ],
[], [],
() => {
expect(createFlash).toHaveBeenCalledTimes(1);
done();
},
); );
expect(createFlash).toHaveBeenCalledTimes(1);
}); });
}); });
......
...@@ -27,9 +27,9 @@ describe('error tracking settings actions', () => { ...@@ -27,9 +27,9 @@ describe('error tracking settings actions', () => {
refreshCurrentPage.mockClear(); refreshCurrentPage.mockClear();
}); });
it('should request and transform the project list', (done) => { it('should request and transform the project list', async () => {
mock.onGet(TEST_HOST).reply(() => [200, { projects: projectList }]); mock.onGet(TEST_HOST).reply(() => [200, { projects: projectList }]);
testAction( await testAction(
actions.fetchProjects, actions.fetchProjects,
null, null,
state, state,
...@@ -41,16 +41,13 @@ describe('error tracking settings actions', () => { ...@@ -41,16 +41,13 @@ describe('error tracking settings actions', () => {
payload: projectList.map(convertObjectPropsToCamelCase), payload: projectList.map(convertObjectPropsToCamelCase),
}, },
], ],
() => {
expect(mock.history.get.length).toBe(1);
done();
},
); );
expect(mock.history.get.length).toBe(1);
}); });
it('should handle a server error', (done) => { it('should handle a server error', async () => {
mock.onGet(`${TEST_HOST}.json`).reply(() => [400]); mock.onGet(`${TEST_HOST}.json`).reply(() => [400]);
testAction( await testAction(
actions.fetchProjects, actions.fetchProjects,
null, null,
state, state,
...@@ -61,27 +58,23 @@ describe('error tracking settings actions', () => { ...@@ -61,27 +58,23 @@ describe('error tracking settings actions', () => {
type: 'receiveProjectsError', type: 'receiveProjectsError',
}, },
], ],
() => {
expect(mock.history.get.length).toBe(1);
done();
},
); );
expect(mock.history.get.length).toBe(1);
}); });
it('should request projects correctly', (done) => { it('should request projects correctly', () => {
testAction( return testAction(
actions.requestProjects, actions.requestProjects,
null, null,
state, state,
[{ type: types.SET_PROJECTS_LOADING, payload: true }, { type: types.RESET_CONNECT }], [{ type: types.SET_PROJECTS_LOADING, payload: true }, { type: types.RESET_CONNECT }],
[], [],
done,
); );
}); });
it('should receive projects correctly', (done) => { it('should receive projects correctly', () => {
const testPayload = []; const testPayload = [];
testAction( return testAction(
actions.receiveProjectsSuccess, actions.receiveProjectsSuccess,
testPayload, testPayload,
state, state,
...@@ -91,13 +84,12 @@ describe('error tracking settings actions', () => { ...@@ -91,13 +84,12 @@ describe('error tracking settings actions', () => {
{ type: types.SET_PROJECTS_LOADING, payload: false }, { type: types.SET_PROJECTS_LOADING, payload: false },
], ],
[], [],
done,
); );
}); });
it('should handle errors when receiving projects', (done) => { it('should handle errors when receiving projects', () => {
const testPayload = []; const testPayload = [];
testAction( return testAction(
actions.receiveProjectsError, actions.receiveProjectsError,
testPayload, testPayload,
state, state,
...@@ -107,7 +99,6 @@ describe('error tracking settings actions', () => { ...@@ -107,7 +99,6 @@ describe('error tracking settings actions', () => {
{ type: types.SET_PROJECTS_LOADING, payload: false }, { type: types.SET_PROJECTS_LOADING, payload: false },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -126,18 +117,16 @@ describe('error tracking settings actions', () => { ...@@ -126,18 +117,16 @@ describe('error tracking settings actions', () => {
mock.restore(); mock.restore();
}); });
it('should save the page', (done) => { it('should save the page', async () => {
mock.onPatch(TEST_HOST).reply(200); mock.onPatch(TEST_HOST).reply(200);
testAction(actions.updateSettings, null, state, [], [{ type: 'requestSettings' }], () => { await testAction(actions.updateSettings, null, state, [], [{ type: 'requestSettings' }]);
expect(mock.history.patch.length).toBe(1); expect(mock.history.patch.length).toBe(1);
expect(refreshCurrentPage).toHaveBeenCalled(); expect(refreshCurrentPage).toHaveBeenCalled();
done();
});
}); });
it('should handle a server error', (done) => { it('should handle a server error', async () => {
mock.onPatch(TEST_HOST).reply(400); mock.onPatch(TEST_HOST).reply(400);
testAction( await testAction(
actions.updateSettings, actions.updateSettings,
null, null,
state, state,
...@@ -149,57 +138,50 @@ describe('error tracking settings actions', () => { ...@@ -149,57 +138,50 @@ describe('error tracking settings actions', () => {
payload: new Error('Request failed with status code 400'), payload: new Error('Request failed with status code 400'),
}, },
], ],
() => {
expect(mock.history.patch.length).toBe(1);
done();
},
); );
expect(mock.history.patch.length).toBe(1);
}); });
it('should request to save the page', (done) => { it('should request to save the page', () => {
testAction( return testAction(
actions.requestSettings, actions.requestSettings,
null, null,
state, state,
[{ type: types.UPDATE_SETTINGS_LOADING, payload: true }], [{ type: types.UPDATE_SETTINGS_LOADING, payload: true }],
[], [],
done,
); );
}); });
it('should handle errors when requesting to save the page', (done) => { it('should handle errors when requesting to save the page', () => {
testAction( return testAction(
actions.receiveSettingsError, actions.receiveSettingsError,
{}, {},
state, state,
[{ type: types.UPDATE_SETTINGS_LOADING, payload: false }], [{ type: types.UPDATE_SETTINGS_LOADING, payload: false }],
[], [],
done,
); );
}); });
}); });
describe('generic actions to update the store', () => { describe('generic actions to update the store', () => {
const testData = 'test'; const testData = 'test';
it('should reset the `connect success` flag when updating the api host', (done) => { it('should reset the `connect success` flag when updating the api host', () => {
testAction( return testAction(
actions.updateApiHost, actions.updateApiHost,
testData, testData,
state, state,
[{ type: types.UPDATE_API_HOST, payload: testData }, { type: types.RESET_CONNECT }], [{ type: types.UPDATE_API_HOST, payload: testData }, { type: types.RESET_CONNECT }],
[], [],
done,
); );
}); });
it('should reset the `connect success` flag when updating the token', (done) => { it('should reset the `connect success` flag when updating the token', () => {
testAction( return testAction(
actions.updateToken, actions.updateToken,
testData, testData,
state, state,
[{ type: types.UPDATE_TOKEN, payload: testData }, { type: types.RESET_CONNECT }], [{ type: types.UPDATE_TOKEN, payload: testData }, { type: types.RESET_CONNECT }],
[], [],
done,
); );
}); });
......
...@@ -40,7 +40,7 @@ describe('Feature flags Edit Module actions', () => { ...@@ -40,7 +40,7 @@ describe('Feature flags Edit Module actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestUpdateFeatureFlag and receiveUpdateFeatureFlagSuccess ', (done) => { it('dispatches requestUpdateFeatureFlag and receiveUpdateFeatureFlagSuccess ', () => {
const featureFlag = { const featureFlag = {
name: 'name', name: 'name',
description: 'description', description: 'description',
...@@ -57,7 +57,7 @@ describe('Feature flags Edit Module actions', () => { ...@@ -57,7 +57,7 @@ describe('Feature flags Edit Module actions', () => {
}; };
mock.onPut(mockedState.endpoint, mapStrategiesToRails(featureFlag)).replyOnce(200); mock.onPut(mockedState.endpoint, mapStrategiesToRails(featureFlag)).replyOnce(200);
testAction( return testAction(
updateFeatureFlag, updateFeatureFlag,
featureFlag, featureFlag,
mockedState, mockedState,
...@@ -70,16 +70,15 @@ describe('Feature flags Edit Module actions', () => { ...@@ -70,16 +70,15 @@ describe('Feature flags Edit Module actions', () => {
type: 'receiveUpdateFeatureFlagSuccess', type: 'receiveUpdateFeatureFlagSuccess',
}, },
], ],
done,
); );
}); });
}); });
describe('error', () => { describe('error', () => {
it('dispatches requestUpdateFeatureFlag and receiveUpdateFeatureFlagError ', (done) => { it('dispatches requestUpdateFeatureFlag and receiveUpdateFeatureFlagError ', () => {
mock.onPut(`${TEST_HOST}/endpoint.json`).replyOnce(500, { message: [] }); mock.onPut(`${TEST_HOST}/endpoint.json`).replyOnce(500, { message: [] });
testAction( return testAction(
updateFeatureFlag, updateFeatureFlag,
{ {
name: 'feature_flag', name: 'feature_flag',
...@@ -97,28 +96,26 @@ describe('Feature flags Edit Module actions', () => { ...@@ -97,28 +96,26 @@ describe('Feature flags Edit Module actions', () => {
payload: { message: [] }, payload: { message: [] },
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('requestUpdateFeatureFlag', () => { describe('requestUpdateFeatureFlag', () => {
it('should commit REQUEST_UPDATE_FEATURE_FLAG mutation', (done) => { it('should commit REQUEST_UPDATE_FEATURE_FLAG mutation', () => {
testAction( return testAction(
requestUpdateFeatureFlag, requestUpdateFeatureFlag,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_UPDATE_FEATURE_FLAG }], [{ type: types.REQUEST_UPDATE_FEATURE_FLAG }],
[], [],
done,
); );
}); });
}); });
describe('receiveUpdateFeatureFlagSuccess', () => { describe('receiveUpdateFeatureFlagSuccess', () => {
it('should commit RECEIVE_UPDATE_FEATURE_FLAG_SUCCESS mutation', (done) => { it('should commit RECEIVE_UPDATE_FEATURE_FLAG_SUCCESS mutation', () => {
testAction( return testAction(
receiveUpdateFeatureFlagSuccess, receiveUpdateFeatureFlagSuccess,
null, null,
mockedState, mockedState,
...@@ -128,20 +125,18 @@ describe('Feature flags Edit Module actions', () => { ...@@ -128,20 +125,18 @@ describe('Feature flags Edit Module actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('receiveUpdateFeatureFlagError', () => { describe('receiveUpdateFeatureFlagError', () => {
it('should commit RECEIVE_UPDATE_FEATURE_FLAG_ERROR mutation', (done) => { it('should commit RECEIVE_UPDATE_FEATURE_FLAG_ERROR mutation', () => {
testAction( return testAction(
receiveUpdateFeatureFlagError, receiveUpdateFeatureFlagError,
'There was an error', 'There was an error',
mockedState, mockedState,
[{ type: types.RECEIVE_UPDATE_FEATURE_FLAG_ERROR, payload: 'There was an error' }], [{ type: types.RECEIVE_UPDATE_FEATURE_FLAG_ERROR, payload: 'There was an error' }],
[], [],
done,
); );
}); });
}); });
...@@ -159,10 +154,10 @@ describe('Feature flags Edit Module actions', () => { ...@@ -159,10 +154,10 @@ describe('Feature flags Edit Module actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestFeatureFlag and receiveFeatureFlagSuccess ', (done) => { it('dispatches requestFeatureFlag and receiveFeatureFlagSuccess ', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`).replyOnce(200, { id: 1 }); mock.onGet(`${TEST_HOST}/endpoint.json`).replyOnce(200, { id: 1 });
testAction( return testAction(
fetchFeatureFlag, fetchFeatureFlag,
{ id: 1 }, { id: 1 },
mockedState, mockedState,
...@@ -176,16 +171,15 @@ describe('Feature flags Edit Module actions', () => { ...@@ -176,16 +171,15 @@ describe('Feature flags Edit Module actions', () => {
payload: { id: 1 }, payload: { id: 1 },
}, },
], ],
done,
); );
}); });
}); });
describe('error', () => { describe('error', () => {
it('dispatches requestFeatureFlag and receiveUpdateFeatureFlagError ', (done) => { it('dispatches requestFeatureFlag and receiveUpdateFeatureFlagError ', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`, {}).replyOnce(500, {}); mock.onGet(`${TEST_HOST}/endpoint.json`, {}).replyOnce(500, {});
testAction( return testAction(
fetchFeatureFlag, fetchFeatureFlag,
null, null,
mockedState, mockedState,
...@@ -198,41 +192,38 @@ describe('Feature flags Edit Module actions', () => { ...@@ -198,41 +192,38 @@ describe('Feature flags Edit Module actions', () => {
type: 'receiveFeatureFlagError', type: 'receiveFeatureFlagError',
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('requestFeatureFlag', () => { describe('requestFeatureFlag', () => {
it('should commit REQUEST_FEATURE_FLAG mutation', (done) => { it('should commit REQUEST_FEATURE_FLAG mutation', () => {
testAction( return testAction(
requestFeatureFlag, requestFeatureFlag,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_FEATURE_FLAG }], [{ type: types.REQUEST_FEATURE_FLAG }],
[], [],
done,
); );
}); });
}); });
describe('receiveFeatureFlagSuccess', () => { describe('receiveFeatureFlagSuccess', () => {
it('should commit RECEIVE_FEATURE_FLAG_SUCCESS mutation', (done) => { it('should commit RECEIVE_FEATURE_FLAG_SUCCESS mutation', () => {
testAction( return testAction(
receiveFeatureFlagSuccess, receiveFeatureFlagSuccess,
{ id: 1 }, { id: 1 },
mockedState, mockedState,
[{ type: types.RECEIVE_FEATURE_FLAG_SUCCESS, payload: { id: 1 } }], [{ type: types.RECEIVE_FEATURE_FLAG_SUCCESS, payload: { id: 1 } }],
[], [],
done,
); );
}); });
}); });
describe('receiveFeatureFlagError', () => { describe('receiveFeatureFlagError', () => {
it('should commit RECEIVE_FEATURE_FLAG_ERROR mutation', (done) => { it('should commit RECEIVE_FEATURE_FLAG_ERROR mutation', () => {
testAction( return testAction(
receiveFeatureFlagError, receiveFeatureFlagError,
null, null,
mockedState, mockedState,
...@@ -242,20 +233,18 @@ describe('Feature flags Edit Module actions', () => { ...@@ -242,20 +233,18 @@ describe('Feature flags Edit Module actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('toggelActive', () => { describe('toggelActive', () => {
it('should commit TOGGLE_ACTIVE mutation', (done) => { it('should commit TOGGLE_ACTIVE mutation', () => {
testAction( return testAction(
toggleActive, toggleActive,
true, true,
mockedState, mockedState,
[{ type: types.TOGGLE_ACTIVE, payload: true }], [{ type: types.TOGGLE_ACTIVE, payload: true }],
[], [],
done,
); );
}); });
}); });
......
...@@ -32,14 +32,13 @@ describe('Feature flags actions', () => { ...@@ -32,14 +32,13 @@ describe('Feature flags actions', () => {
}); });
describe('setFeatureFlagsOptions', () => { describe('setFeatureFlagsOptions', () => {
it('should commit SET_FEATURE_FLAGS_OPTIONS mutation', (done) => { it('should commit SET_FEATURE_FLAGS_OPTIONS mutation', () => {
testAction( return testAction(
setFeatureFlagsOptions, setFeatureFlagsOptions,
{ page: '1', scope: 'all' }, { page: '1', scope: 'all' },
mockedState, mockedState,
[{ type: types.SET_FEATURE_FLAGS_OPTIONS, payload: { page: '1', scope: 'all' } }], [{ type: types.SET_FEATURE_FLAGS_OPTIONS, payload: { page: '1', scope: 'all' } }],
[], [],
done,
); );
}); });
}); });
...@@ -57,10 +56,10 @@ describe('Feature flags actions', () => { ...@@ -57,10 +56,10 @@ describe('Feature flags actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestFeatureFlags and receiveFeatureFlagsSuccess ', (done) => { it('dispatches requestFeatureFlags and receiveFeatureFlagsSuccess ', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`).replyOnce(200, getRequestData, {}); mock.onGet(`${TEST_HOST}/endpoint.json`).replyOnce(200, getRequestData, {});
testAction( return testAction(
fetchFeatureFlags, fetchFeatureFlags,
null, null,
mockedState, mockedState,
...@@ -74,16 +73,15 @@ describe('Feature flags actions', () => { ...@@ -74,16 +73,15 @@ describe('Feature flags actions', () => {
type: 'receiveFeatureFlagsSuccess', type: 'receiveFeatureFlagsSuccess',
}, },
], ],
done,
); );
}); });
}); });
describe('error', () => { describe('error', () => {
it('dispatches requestFeatureFlags and receiveFeatureFlagsError ', (done) => { it('dispatches requestFeatureFlags and receiveFeatureFlagsError ', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`, {}).replyOnce(500, {}); mock.onGet(`${TEST_HOST}/endpoint.json`, {}).replyOnce(500, {});
testAction( return testAction(
fetchFeatureFlags, fetchFeatureFlags,
null, null,
mockedState, mockedState,
...@@ -96,28 +94,26 @@ describe('Feature flags actions', () => { ...@@ -96,28 +94,26 @@ describe('Feature flags actions', () => {
type: 'receiveFeatureFlagsError', type: 'receiveFeatureFlagsError',
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('requestFeatureFlags', () => { describe('requestFeatureFlags', () => {
it('should commit RECEIVE_FEATURE_FLAGS_SUCCESS mutation', (done) => { it('should commit RECEIVE_FEATURE_FLAGS_SUCCESS mutation', () => {
testAction( return testAction(
requestFeatureFlags, requestFeatureFlags,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_FEATURE_FLAGS }], [{ type: types.REQUEST_FEATURE_FLAGS }],
[], [],
done,
); );
}); });
}); });
describe('receiveFeatureFlagsSuccess', () => { describe('receiveFeatureFlagsSuccess', () => {
it('should commit RECEIVE_FEATURE_FLAGS_SUCCESS mutation', (done) => { it('should commit RECEIVE_FEATURE_FLAGS_SUCCESS mutation', () => {
testAction( return testAction(
receiveFeatureFlagsSuccess, receiveFeatureFlagsSuccess,
{ data: getRequestData, headers: {} }, { data: getRequestData, headers: {} },
mockedState, mockedState,
...@@ -128,20 +124,18 @@ describe('Feature flags actions', () => { ...@@ -128,20 +124,18 @@ describe('Feature flags actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('receiveFeatureFlagsError', () => { describe('receiveFeatureFlagsError', () => {
it('should commit RECEIVE_FEATURE_FLAGS_ERROR mutation', (done) => { it('should commit RECEIVE_FEATURE_FLAGS_ERROR mutation', () => {
testAction( return testAction(
receiveFeatureFlagsError, receiveFeatureFlagsError,
null, null,
mockedState, mockedState,
[{ type: types.RECEIVE_FEATURE_FLAGS_ERROR }], [{ type: types.RECEIVE_FEATURE_FLAGS_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -159,10 +153,10 @@ describe('Feature flags actions', () => { ...@@ -159,10 +153,10 @@ describe('Feature flags actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestRotateInstanceId and receiveRotateInstanceIdSuccess ', (done) => { it('dispatches requestRotateInstanceId and receiveRotateInstanceIdSuccess ', () => {
mock.onPost(`${TEST_HOST}/endpoint.json`).replyOnce(200, rotateData, {}); mock.onPost(`${TEST_HOST}/endpoint.json`).replyOnce(200, rotateData, {});
testAction( return testAction(
rotateInstanceId, rotateInstanceId,
null, null,
mockedState, mockedState,
...@@ -176,16 +170,15 @@ describe('Feature flags actions', () => { ...@@ -176,16 +170,15 @@ describe('Feature flags actions', () => {
type: 'receiveRotateInstanceIdSuccess', type: 'receiveRotateInstanceIdSuccess',
}, },
], ],
done,
); );
}); });
}); });
describe('error', () => { describe('error', () => {
it('dispatches requestRotateInstanceId and receiveRotateInstanceIdError ', (done) => { it('dispatches requestRotateInstanceId and receiveRotateInstanceIdError ', () => {
mock.onGet(`${TEST_HOST}/endpoint.json`, {}).replyOnce(500, {}); mock.onGet(`${TEST_HOST}/endpoint.json`, {}).replyOnce(500, {});
testAction( return testAction(
rotateInstanceId, rotateInstanceId,
null, null,
mockedState, mockedState,
...@@ -198,28 +191,26 @@ describe('Feature flags actions', () => { ...@@ -198,28 +191,26 @@ describe('Feature flags actions', () => {
type: 'receiveRotateInstanceIdError', type: 'receiveRotateInstanceIdError',
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('requestRotateInstanceId', () => { describe('requestRotateInstanceId', () => {
it('should commit REQUEST_ROTATE_INSTANCE_ID mutation', (done) => { it('should commit REQUEST_ROTATE_INSTANCE_ID mutation', () => {
testAction( return testAction(
requestRotateInstanceId, requestRotateInstanceId,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_ROTATE_INSTANCE_ID }], [{ type: types.REQUEST_ROTATE_INSTANCE_ID }],
[], [],
done,
); );
}); });
}); });
describe('receiveRotateInstanceIdSuccess', () => { describe('receiveRotateInstanceIdSuccess', () => {
it('should commit RECEIVE_ROTATE_INSTANCE_ID_SUCCESS mutation', (done) => { it('should commit RECEIVE_ROTATE_INSTANCE_ID_SUCCESS mutation', () => {
testAction( return testAction(
receiveRotateInstanceIdSuccess, receiveRotateInstanceIdSuccess,
{ data: rotateData, headers: {} }, { data: rotateData, headers: {} },
mockedState, mockedState,
...@@ -230,20 +221,18 @@ describe('Feature flags actions', () => { ...@@ -230,20 +221,18 @@ describe('Feature flags actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('receiveRotateInstanceIdError', () => { describe('receiveRotateInstanceIdError', () => {
it('should commit RECEIVE_ROTATE_INSTANCE_ID_ERROR mutation', (done) => { it('should commit RECEIVE_ROTATE_INSTANCE_ID_ERROR mutation', () => {
testAction( return testAction(
receiveRotateInstanceIdError, receiveRotateInstanceIdError,
null, null,
mockedState, mockedState,
[{ type: types.RECEIVE_ROTATE_INSTANCE_ID_ERROR }], [{ type: types.RECEIVE_ROTATE_INSTANCE_ID_ERROR }],
[], [],
done,
); );
}); });
}); });
...@@ -262,10 +251,10 @@ describe('Feature flags actions', () => { ...@@ -262,10 +251,10 @@ describe('Feature flags actions', () => {
mock.restore(); mock.restore();
}); });
describe('success', () => { describe('success', () => {
it('dispatches updateFeatureFlag and receiveUpdateFeatureFlagSuccess', (done) => { it('dispatches updateFeatureFlag and receiveUpdateFeatureFlagSuccess', () => {
mock.onPut(featureFlag.update_path).replyOnce(200, featureFlag, {}); mock.onPut(featureFlag.update_path).replyOnce(200, featureFlag, {});
testAction( return testAction(
toggleFeatureFlag, toggleFeatureFlag,
featureFlag, featureFlag,
mockedState, mockedState,
...@@ -280,15 +269,15 @@ describe('Feature flags actions', () => { ...@@ -280,15 +269,15 @@ describe('Feature flags actions', () => {
type: 'receiveUpdateFeatureFlagSuccess', type: 'receiveUpdateFeatureFlagSuccess',
}, },
], ],
done,
); );
}); });
}); });
describe('error', () => { describe('error', () => {
it('dispatches updateFeatureFlag and receiveUpdateFeatureFlagSuccess', (done) => { it('dispatches updateFeatureFlag and receiveUpdateFeatureFlagSuccess', () => {
mock.onPut(featureFlag.update_path).replyOnce(500); mock.onPut(featureFlag.update_path).replyOnce(500);
testAction( return testAction(
toggleFeatureFlag, toggleFeatureFlag,
featureFlag, featureFlag,
mockedState, mockedState,
...@@ -303,7 +292,6 @@ describe('Feature flags actions', () => { ...@@ -303,7 +292,6 @@ describe('Feature flags actions', () => {
type: 'receiveUpdateFeatureFlagError', type: 'receiveUpdateFeatureFlagError',
}, },
], ],
done,
); );
}); });
}); });
...@@ -315,8 +303,8 @@ describe('Feature flags actions', () => { ...@@ -315,8 +303,8 @@ describe('Feature flags actions', () => {
})); }));
}); });
it('commits UPDATE_FEATURE_FLAG with the given flag', (done) => { it('commits UPDATE_FEATURE_FLAG with the given flag', () => {
testAction( return testAction(
updateFeatureFlag, updateFeatureFlag,
featureFlag, featureFlag,
mockedState, mockedState,
...@@ -327,7 +315,6 @@ describe('Feature flags actions', () => { ...@@ -327,7 +315,6 @@ describe('Feature flags actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -338,8 +325,8 @@ describe('Feature flags actions', () => { ...@@ -338,8 +325,8 @@ describe('Feature flags actions', () => {
})); }));
}); });
it('commits RECEIVE_UPDATE_FEATURE_FLAG_SUCCESS with the given flag', (done) => { it('commits RECEIVE_UPDATE_FEATURE_FLAG_SUCCESS with the given flag', () => {
testAction( return testAction(
receiveUpdateFeatureFlagSuccess, receiveUpdateFeatureFlagSuccess,
featureFlag, featureFlag,
mockedState, mockedState,
...@@ -350,7 +337,6 @@ describe('Feature flags actions', () => { ...@@ -350,7 +337,6 @@ describe('Feature flags actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
...@@ -361,8 +347,8 @@ describe('Feature flags actions', () => { ...@@ -361,8 +347,8 @@ describe('Feature flags actions', () => {
})); }));
}); });
it('commits RECEIVE_UPDATE_FEATURE_FLAG_ERROR with the given flag id', (done) => { it('commits RECEIVE_UPDATE_FEATURE_FLAG_ERROR with the given flag id', () => {
testAction( return testAction(
receiveUpdateFeatureFlagError, receiveUpdateFeatureFlagError,
featureFlag.id, featureFlag.id,
mockedState, mockedState,
...@@ -373,22 +359,20 @@ describe('Feature flags actions', () => { ...@@ -373,22 +359,20 @@ describe('Feature flags actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('clearAlert', () => { describe('clearAlert', () => {
it('should commit RECEIVE_CLEAR_ALERT', (done) => { it('should commit RECEIVE_CLEAR_ALERT', () => {
const alertIndex = 3; const alertIndex = 3;
testAction( return testAction(
clearAlert, clearAlert,
alertIndex, alertIndex,
mockedState, mockedState,
[{ type: 'RECEIVE_CLEAR_ALERT', payload: alertIndex }], [{ type: 'RECEIVE_CLEAR_ALERT', payload: alertIndex }],
[], [],
done,
); );
}); });
}); });
......
...@@ -33,7 +33,7 @@ describe('Feature flags New Module Actions', () => { ...@@ -33,7 +33,7 @@ describe('Feature flags New Module Actions', () => {
}); });
describe('success', () => { describe('success', () => {
it('dispatches requestCreateFeatureFlag and receiveCreateFeatureFlagSuccess ', (done) => { it('dispatches requestCreateFeatureFlag and receiveCreateFeatureFlagSuccess ', () => {
const actionParams = { const actionParams = {
name: 'name', name: 'name',
description: 'description', description: 'description',
...@@ -50,7 +50,7 @@ describe('Feature flags New Module Actions', () => { ...@@ -50,7 +50,7 @@ describe('Feature flags New Module Actions', () => {
}; };
mock.onPost(mockedState.endpoint, mapStrategiesToRails(actionParams)).replyOnce(200); mock.onPost(mockedState.endpoint, mapStrategiesToRails(actionParams)).replyOnce(200);
testAction( return testAction(
createFeatureFlag, createFeatureFlag,
actionParams, actionParams,
mockedState, mockedState,
...@@ -63,13 +63,12 @@ describe('Feature flags New Module Actions', () => { ...@@ -63,13 +63,12 @@ describe('Feature flags New Module Actions', () => {
type: 'receiveCreateFeatureFlagSuccess', type: 'receiveCreateFeatureFlagSuccess',
}, },
], ],
done,
); );
}); });
}); });
describe('error', () => { describe('error', () => {
it('dispatches requestCreateFeatureFlag and receiveCreateFeatureFlagError ', (done) => { it('dispatches requestCreateFeatureFlag and receiveCreateFeatureFlagError ', () => {
const actionParams = { const actionParams = {
name: 'name', name: 'name',
description: 'description', description: 'description',
...@@ -88,7 +87,7 @@ describe('Feature flags New Module Actions', () => { ...@@ -88,7 +87,7 @@ describe('Feature flags New Module Actions', () => {
.onPost(mockedState.endpoint, mapStrategiesToRails(actionParams)) .onPost(mockedState.endpoint, mapStrategiesToRails(actionParams))
.replyOnce(500, { message: [] }); .replyOnce(500, { message: [] });
testAction( return testAction(
createFeatureFlag, createFeatureFlag,
actionParams, actionParams,
mockedState, mockedState,
...@@ -102,28 +101,26 @@ describe('Feature flags New Module Actions', () => { ...@@ -102,28 +101,26 @@ describe('Feature flags New Module Actions', () => {
payload: { message: [] }, payload: { message: [] },
}, },
], ],
done,
); );
}); });
}); });
}); });
describe('requestCreateFeatureFlag', () => { describe('requestCreateFeatureFlag', () => {
it('should commit REQUEST_CREATE_FEATURE_FLAG mutation', (done) => { it('should commit REQUEST_CREATE_FEATURE_FLAG mutation', () => {
testAction( return testAction(
requestCreateFeatureFlag, requestCreateFeatureFlag,
null, null,
mockedState, mockedState,
[{ type: types.REQUEST_CREATE_FEATURE_FLAG }], [{ type: types.REQUEST_CREATE_FEATURE_FLAG }],
[], [],
done,
); );
}); });
}); });
describe('receiveCreateFeatureFlagSuccess', () => { describe('receiveCreateFeatureFlagSuccess', () => {
it('should commit RECEIVE_CREATE_FEATURE_FLAG_SUCCESS mutation', (done) => { it('should commit RECEIVE_CREATE_FEATURE_FLAG_SUCCESS mutation', () => {
testAction( return testAction(
receiveCreateFeatureFlagSuccess, receiveCreateFeatureFlagSuccess,
null, null,
mockedState, mockedState,
...@@ -133,20 +130,18 @@ describe('Feature flags New Module Actions', () => { ...@@ -133,20 +130,18 @@ describe('Feature flags New Module Actions', () => {
}, },
], ],
[], [],
done,
); );
}); });
}); });
describe('receiveCreateFeatureFlagError', () => { describe('receiveCreateFeatureFlagError', () => {
it('should commit RECEIVE_CREATE_FEATURE_FLAG_ERROR mutation', (done) => { it('should commit RECEIVE_CREATE_FEATURE_FLAG_ERROR mutation', () => {
testAction( return testAction(
receiveCreateFeatureFlagError, receiveCreateFeatureFlagError,
'There was an error', 'There was an error',
mockedState, mockedState,
[{ type: types.RECEIVE_CREATE_FEATURE_FLAG_ERROR, payload: 'There was an error' }], [{ type: types.RECEIVE_CREATE_FEATURE_FLAG_ERROR, payload: 'There was an error' }],
[], [],
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