Commit 94027a97 authored by Peter Hegman's avatar Peter Hegman

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

Remove jest test callbacks from IDE specs

See merge request gitlab-org/gitlab!84477
parents 794a90a1 10109de8
......@@ -69,25 +69,21 @@ describe('new dropdown upload', () => {
jest.spyOn(FileReader.prototype, 'readAsText');
});
it('calls readAsText and creates file in plain text (without encoding) if the file content is plain text', (done) => {
it('calls readAsText and creates file in plain text (without encoding) if the file content is plain text', async () => {
const waitForCreate = new Promise((resolve) => vm.$on('create', resolve));
vm.createFile(textTarget, textFile);
expect(FileReader.prototype.readAsText).toHaveBeenCalledWith(textFile);
waitForCreate
.then(() => {
expect(vm.$emit).toHaveBeenCalledWith('create', {
name: textFile.name,
type: 'blob',
content: 'plain text',
rawPath: '',
mimeType: 'test/mime-text',
});
})
.then(done)
.catch(done.fail);
await waitForCreate;
expect(vm.$emit).toHaveBeenCalledWith('create', {
name: textFile.name,
type: 'blob',
content: 'plain text',
rawPath: '',
mimeType: 'test/mime-text',
});
});
it('creates a blob URL for the content if binary', () => {
......
......@@ -63,56 +63,47 @@ describe('IDE store merge request actions', () => {
mock.onGet(/api\/(.*)\/projects\/abcproject\/merge_requests/).reply(200, mockData);
});
it('calls getProjectMergeRequests service method', (done) => {
store
.dispatch('getMergeRequestsForBranch', { projectId: TEST_PROJECT, branchId: 'bar' })
.then(() => {
expect(service.getProjectMergeRequests).toHaveBeenCalledWith(TEST_PROJECT, {
source_branch: 'bar',
source_project_id: TEST_PROJECT_ID,
state: 'opened',
order_by: 'created_at',
per_page: 1,
});
done();
})
.catch(done.fail);
it('calls getProjectMergeRequests service method', async () => {
await store.dispatch('getMergeRequestsForBranch', {
projectId: TEST_PROJECT,
branchId: 'bar',
});
expect(service.getProjectMergeRequests).toHaveBeenCalledWith(TEST_PROJECT, {
source_branch: 'bar',
source_project_id: TEST_PROJECT_ID,
state: 'opened',
order_by: 'created_at',
per_page: 1,
});
});
it('sets the "Merge Request" Object', (done) => {
store
.dispatch('getMergeRequestsForBranch', { projectId: TEST_PROJECT, branchId: 'bar' })
.then(() => {
expect(store.state.projects.abcproject.mergeRequests).toEqual({
2: expect.objectContaining(mrData),
});
done();
})
.catch(done.fail);
it('sets the "Merge Request" Object', async () => {
await store.dispatch('getMergeRequestsForBranch', {
projectId: TEST_PROJECT,
branchId: 'bar',
});
expect(store.state.projects.abcproject.mergeRequests).toEqual({
2: expect.objectContaining(mrData),
});
});
it('sets "Current Merge Request" object to the most recent MR', (done) => {
store
.dispatch('getMergeRequestsForBranch', { projectId: TEST_PROJECT, branchId: 'bar' })
.then(() => {
expect(store.state.currentMergeRequestId).toEqual('2');
done();
})
.catch(done.fail);
it('sets "Current Merge Request" object to the most recent MR', async () => {
await store.dispatch('getMergeRequestsForBranch', {
projectId: TEST_PROJECT,
branchId: 'bar',
});
expect(store.state.currentMergeRequestId).toEqual('2');
});
it('does nothing if user cannot read MRs', (done) => {
it('does nothing if user cannot read MRs', async () => {
store.state.projects[TEST_PROJECT].userPermissions[PERMISSION_READ_MR] = false;
store
.dispatch('getMergeRequestsForBranch', { projectId: TEST_PROJECT, branchId: 'bar' })
.then(() => {
expect(service.getProjectMergeRequests).not.toHaveBeenCalled();
expect(store.state.currentMergeRequestId).toBe('');
})
.then(done)
.catch(done.fail);
await store.dispatch('getMergeRequestsForBranch', {
projectId: TEST_PROJECT,
branchId: 'bar',
});
expect(service.getProjectMergeRequests).not.toHaveBeenCalled();
expect(store.state.currentMergeRequestId).toBe('');
});
});
......@@ -122,15 +113,13 @@ describe('IDE store merge request actions', () => {
mock.onGet(/api\/(.*)\/projects\/abcproject\/merge_requests/).reply(200, []);
});
it('does not fail if there are no merge requests for current branch', (done) => {
store
.dispatch('getMergeRequestsForBranch', { projectId: TEST_PROJECT, branchId: 'foo' })
.then(() => {
expect(store.state.projects[TEST_PROJECT].mergeRequests).toEqual({});
expect(store.state.currentMergeRequestId).toEqual('');
done();
})
.catch(done.fail);
it('does not fail if there are no merge requests for current branch', async () => {
await store.dispatch('getMergeRequestsForBranch', {
projectId: TEST_PROJECT,
branchId: 'foo',
});
expect(store.state.projects[TEST_PROJECT].mergeRequests).toEqual({});
expect(store.state.currentMergeRequestId).toEqual('');
});
});
});
......@@ -140,17 +129,18 @@ describe('IDE store merge request actions', () => {
mock.onGet(/api\/(.*)\/projects\/abcproject\/merge_requests/).networkError();
});
it('flashes message, if error', (done) => {
store
.dispatch('getMergeRequestsForBranch', { projectId: TEST_PROJECT, branchId: 'bar' })
it('flashes message, if error', () => {
return store
.dispatch('getMergeRequestsForBranch', {
projectId: TEST_PROJECT,
branchId: 'bar',
})
.catch(() => {
expect(createFlash).toHaveBeenCalled();
expect(createFlash.mock.calls[0][0].message).toBe(
'Error fetching merge requests for bar',
);
})
.then(done)
.catch(done.fail);
});
});
});
});
......@@ -165,29 +155,15 @@ describe('IDE store merge request actions', () => {
.reply(200, { title: 'mergerequest' });
});
it('calls getProjectMergeRequestData service method', (done) => {
store
.dispatch('getMergeRequestData', { projectId: TEST_PROJECT, mergeRequestId: 1 })
.then(() => {
expect(service.getProjectMergeRequestData).toHaveBeenCalledWith(TEST_PROJECT, 1);
done();
})
.catch(done.fail);
it('calls getProjectMergeRequestData service method', async () => {
await store.dispatch('getMergeRequestData', { projectId: TEST_PROJECT, mergeRequestId: 1 });
expect(service.getProjectMergeRequestData).toHaveBeenCalledWith(TEST_PROJECT, 1);
});
it('sets the Merge Request Object', (done) => {
store
.dispatch('getMergeRequestData', { projectId: TEST_PROJECT, mergeRequestId: 1 })
.then(() => {
expect(store.state.currentMergeRequestId).toBe(1);
expect(store.state.projects[TEST_PROJECT].mergeRequests['1'].title).toBe(
'mergerequest',
);
done();
})
.catch(done.fail);
it('sets the Merge Request Object', async () => {
await store.dispatch('getMergeRequestData', { projectId: TEST_PROJECT, mergeRequestId: 1 });
expect(store.state.currentMergeRequestId).toBe(1);
expect(store.state.projects[TEST_PROJECT].mergeRequests['1'].title).toBe('mergerequest');
});
});
......@@ -196,32 +172,28 @@ describe('IDE store merge request actions', () => {
mock.onGet(/api\/(.*)\/projects\/abcproject\/merge_requests\/1/).networkError();
});
it('dispatches error action', (done) => {
it('dispatches error action', () => {
const dispatch = jest.fn();
getMergeRequestData(
return getMergeRequestData(
{
commit() {},
dispatch,
state: store.state,
},
{ projectId: TEST_PROJECT, mergeRequestId: 1 },
)
.then(done.fail)
.catch(() => {
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading the merge request.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: {
projectId: TEST_PROJECT,
mergeRequestId: 1,
force: false,
},
});
done();
).catch(() => {
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading the merge request.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: {
projectId: TEST_PROJECT,
mergeRequestId: 1,
force: false,
},
});
});
});
});
});
......@@ -240,27 +212,22 @@ describe('IDE store merge request actions', () => {
.reply(200, { title: 'mergerequest' });
});
it('calls getProjectMergeRequestChanges service method', (done) => {
store
.dispatch('getMergeRequestChanges', { projectId: TEST_PROJECT, mergeRequestId: 1 })
.then(() => {
expect(service.getProjectMergeRequestChanges).toHaveBeenCalledWith(TEST_PROJECT, 1);
done();
})
.catch(done.fail);
it('calls getProjectMergeRequestChanges service method', async () => {
await store.dispatch('getMergeRequestChanges', {
projectId: TEST_PROJECT,
mergeRequestId: 1,
});
expect(service.getProjectMergeRequestChanges).toHaveBeenCalledWith(TEST_PROJECT, 1);
});
it('sets the Merge Request Changes Object', (done) => {
store
.dispatch('getMergeRequestChanges', { projectId: TEST_PROJECT, mergeRequestId: 1 })
.then(() => {
expect(store.state.projects[TEST_PROJECT].mergeRequests['1'].changes.title).toBe(
'mergerequest',
);
done();
})
.catch(done.fail);
it('sets the Merge Request Changes Object', async () => {
await store.dispatch('getMergeRequestChanges', {
projectId: TEST_PROJECT,
mergeRequestId: 1,
});
expect(store.state.projects[TEST_PROJECT].mergeRequests['1'].changes.title).toBe(
'mergerequest',
);
});
});
......@@ -269,32 +236,30 @@ describe('IDE store merge request actions', () => {
mock.onGet(/api\/(.*)\/projects\/abcproject\/merge_requests\/1\/changes/).networkError();
});
it('dispatches error action', (done) => {
it('dispatches error action', async () => {
const dispatch = jest.fn();
getMergeRequestChanges(
{
commit() {},
dispatch,
state: store.state,
await expect(
getMergeRequestChanges(
{
commit() {},
dispatch,
state: store.state,
},
{ projectId: TEST_PROJECT, mergeRequestId: 1 },
),
).rejects.toEqual(new Error('Merge request changes not loaded abcproject'));
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading the merge request changes.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: {
projectId: TEST_PROJECT,
mergeRequestId: 1,
force: false,
},
{ projectId: TEST_PROJECT, mergeRequestId: 1 },
)
.then(done.fail)
.catch(() => {
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading the merge request changes.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: {
projectId: TEST_PROJECT,
mergeRequestId: 1,
force: false,
},
});
done();
});
});
});
});
});
......@@ -312,25 +277,20 @@ describe('IDE store merge request actions', () => {
jest.spyOn(service, 'getProjectMergeRequestVersions');
});
it('calls getProjectMergeRequestVersions service method', (done) => {
store
.dispatch('getMergeRequestVersions', { projectId: TEST_PROJECT, mergeRequestId: 1 })
.then(() => {
expect(service.getProjectMergeRequestVersions).toHaveBeenCalledWith(TEST_PROJECT, 1);
done();
})
.catch(done.fail);
it('calls getProjectMergeRequestVersions service method', async () => {
await store.dispatch('getMergeRequestVersions', {
projectId: TEST_PROJECT,
mergeRequestId: 1,
});
expect(service.getProjectMergeRequestVersions).toHaveBeenCalledWith(TEST_PROJECT, 1);
});
it('sets the Merge Request Versions Object', (done) => {
store
.dispatch('getMergeRequestVersions', { projectId: TEST_PROJECT, mergeRequestId: 1 })
.then(() => {
expect(store.state.projects[TEST_PROJECT].mergeRequests['1'].versions.length).toBe(1);
done();
})
.catch(done.fail);
it('sets the Merge Request Versions Object', async () => {
await store.dispatch('getMergeRequestVersions', {
projectId: TEST_PROJECT,
mergeRequestId: 1,
});
expect(store.state.projects[TEST_PROJECT].mergeRequests['1'].versions.length).toBe(1);
});
});
......@@ -339,32 +299,28 @@ describe('IDE store merge request actions', () => {
mock.onGet(/api\/(.*)\/projects\/abcproject\/merge_requests\/1\/versions/).networkError();
});
it('dispatches error action', (done) => {
it('dispatches error action', () => {
const dispatch = jest.fn();
getMergeRequestVersions(
return getMergeRequestVersions(
{
commit() {},
dispatch,
state: store.state,
},
{ projectId: TEST_PROJECT, mergeRequestId: 1 },
)
.then(done.fail)
.catch(() => {
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading the merge request version data.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: {
projectId: TEST_PROJECT,
mergeRequestId: 1,
force: false,
},
});
done();
).catch(() => {
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading the merge request version data.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: {
projectId: TEST_PROJECT,
mergeRequestId: 1,
force: false,
},
});
});
});
});
});
......@@ -503,37 +459,36 @@ describe('IDE store merge request actions', () => {
);
});
it('dispatches actions for merge request data', (done) => {
openMergeRequest({ state: store.state, dispatch: store.dispatch, getters: mockGetters }, mr)
.then(() => {
expect(store.dispatch.mock.calls).toEqual([
['getMergeRequestData', mr],
['setCurrentBranchId', testMergeRequest.source_branch],
[
'getBranchData',
{
projectId: mr.projectId,
branchId: testMergeRequest.source_branch,
},
],
[
'getFiles',
{
projectId: mr.projectId,
branchId: testMergeRequest.source_branch,
ref: 'abcd2322',
},
],
['getMergeRequestVersions', mr],
['getMergeRequestChanges', mr],
['openMergeRequestChanges', testMergeRequestChanges.changes],
]);
})
.then(done)
.catch(done.fail);
it('dispatches actions for merge request data', async () => {
await openMergeRequest(
{ state: store.state, dispatch: store.dispatch, getters: mockGetters },
mr,
);
expect(store.dispatch.mock.calls).toEqual([
['getMergeRequestData', mr],
['setCurrentBranchId', testMergeRequest.source_branch],
[
'getBranchData',
{
projectId: mr.projectId,
branchId: testMergeRequest.source_branch,
},
],
[
'getFiles',
{
projectId: mr.projectId,
branchId: testMergeRequest.source_branch,
ref: 'abcd2322',
},
],
['getMergeRequestVersions', mr],
['getMergeRequestChanges', mr],
['openMergeRequestChanges', testMergeRequestChanges.changes],
]);
});
it('updates activity bar view and gets file data, if changes are found', (done) => {
it('updates activity bar view and gets file data, if changes are found', async () => {
store.state.entries.foo = {
type: 'blob',
path: 'foo',
......@@ -548,28 +503,24 @@ describe('IDE store merge request actions', () => {
{ new_path: 'bar', path: 'bar' },
];
openMergeRequest({ state: store.state, dispatch: store.dispatch, getters: mockGetters }, mr)
.then(() => {
expect(store.dispatch).toHaveBeenCalledWith(
'openMergeRequestChanges',
testMergeRequestChanges.changes,
);
})
.then(done)
.catch(done.fail);
await openMergeRequest(
{ state: store.state, dispatch: store.dispatch, getters: mockGetters },
mr,
);
expect(store.dispatch).toHaveBeenCalledWith(
'openMergeRequestChanges',
testMergeRequestChanges.changes,
);
});
it('flashes message, if error', (done) => {
it('flashes message, if error', () => {
store.dispatch.mockRejectedValue();
openMergeRequest(store, mr)
.catch(() => {
expect(createFlash).toHaveBeenCalledWith({
message: expect.any(String),
});
})
.then(done)
.catch(done.fail);
return openMergeRequest(store, mr).catch(() => {
expect(createFlash).toHaveBeenCalledWith({
message: expect.any(String),
});
});
});
});
});
......@@ -146,22 +146,16 @@ describe('IDE store project actions', () => {
});
});
it('calls the service', (done) => {
store
.dispatch('refreshLastCommitData', {
projectId: store.state.currentProjectId,
branchId: store.state.currentBranchId,
})
.then(() => {
expect(service.getBranchData).toHaveBeenCalledWith('abc/def', 'main');
done();
})
.catch(done.fail);
it('calls the service', async () => {
await store.dispatch('refreshLastCommitData', {
projectId: store.state.currentProjectId,
branchId: store.state.currentBranchId,
});
expect(service.getBranchData).toHaveBeenCalledWith('abc/def', 'main');
});
it('commits getBranchData', (done) => {
testAction(
it('commits getBranchData', () => {
return testAction(
refreshLastCommitData,
{
projectId: store.state.currentProjectId,
......@@ -181,14 +175,13 @@ describe('IDE store project actions', () => {
],
// action
[],
done,
);
});
});
describe('showBranchNotFoundError', () => {
it('dispatches setErrorMessage', (done) => {
testAction(
it('dispatches setErrorMessage', () => {
return testAction(
showBranchNotFoundError,
'main',
null,
......@@ -204,7 +197,6 @@ describe('IDE store project actions', () => {
},
},
],
done,
);
});
});
......@@ -216,8 +208,8 @@ describe('IDE store project actions', () => {
jest.spyOn(api, 'createBranch').mockResolvedValue();
});
it('calls API', (done) => {
createNewBranchFromDefault(
it('calls API', async () => {
await createNewBranchFromDefault(
{
state: {
currentProjectId: 'project-path',
......@@ -230,21 +222,17 @@ describe('IDE store project actions', () => {
dispatch() {},
},
'new-branch-name',
)
.then(() => {
expect(api.createBranch).toHaveBeenCalledWith('project-path', {
ref: 'main',
branch: 'new-branch-name',
});
})
.then(done)
.catch(done.fail);
);
expect(api.createBranch).toHaveBeenCalledWith('project-path', {
ref: 'main',
branch: 'new-branch-name',
});
});
it('clears error message', (done) => {
it('clears error message', async () => {
const dispatchSpy = jest.fn().mockName('dispatch');
createNewBranchFromDefault(
await createNewBranchFromDefault(
{
state: {
currentProjectId: 'project-path',
......@@ -257,16 +245,12 @@ describe('IDE store project actions', () => {
dispatch: dispatchSpy,
},
'new-branch-name',
)
.then(() => {
expect(dispatchSpy).toHaveBeenCalledWith('setErrorMessage', null);
})
.then(done)
.catch(done.fail);
);
expect(dispatchSpy).toHaveBeenCalledWith('setErrorMessage', null);
});
it('reloads window', (done) => {
createNewBranchFromDefault(
it('reloads window', async () => {
await createNewBranchFromDefault(
{
state: {
currentProjectId: 'project-path',
......@@ -279,18 +263,14 @@ describe('IDE store project actions', () => {
dispatch() {},
},
'new-branch-name',
)
.then(() => {
expect(window.location.reload).toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
);
expect(window.location.reload).toHaveBeenCalled();
});
});
describe('loadEmptyBranch', () => {
it('creates a blank tree and sets loading state to false', (done) => {
testAction(
it('creates a blank tree and sets loading state to false', () => {
return testAction(
loadEmptyBranch,
{ projectId: TEST_PROJECT_ID, branchId: 'main' },
store.state,
......@@ -302,20 +282,18 @@ describe('IDE store project actions', () => {
},
],
expect.any(Object),
done,
);
});
it('does nothing, if tree already exists', (done) => {
it('does nothing, if tree already exists', () => {
const trees = { [`${TEST_PROJECT_ID}/main`]: [] };
testAction(
return testAction(
loadEmptyBranch,
{ projectId: TEST_PROJECT_ID, branchId: 'main' },
{ trees },
[],
[],
done,
);
});
});
......@@ -372,56 +350,48 @@ describe('IDE store project actions', () => {
const branchId = '123-lorem';
const ref = 'abcd2322';
it('when empty repo, loads empty branch', (done) => {
it('when empty repo, loads empty branch', () => {
const mockGetters = { emptyRepo: true };
testAction(
return testAction(
loadBranch,
{ projectId, branchId },
{ ...store.state, ...mockGetters },
[],
[{ type: 'loadEmptyBranch', payload: { projectId, branchId } }],
done,
);
});
it('when branch already exists, does nothing', (done) => {
it('when branch already exists, does nothing', () => {
store.state.projects[projectId].branches[branchId] = {};
testAction(loadBranch, { projectId, branchId }, store.state, [], [], done);
return testAction(loadBranch, { projectId, branchId }, store.state, [], []);
});
it('fetches branch data', (done) => {
it('fetches branch data', async () => {
const mockGetters = { findBranch: () => ({ commit: { id: ref } }) };
jest.spyOn(store, 'dispatch').mockResolvedValue();
loadBranch(
await loadBranch(
{ getters: mockGetters, state: store.state, dispatch: store.dispatch },
{ projectId, branchId },
)
.then(() => {
expect(store.dispatch.mock.calls).toEqual([
['getBranchData', { projectId, branchId }],
['getMergeRequestsForBranch', { projectId, branchId }],
['getFiles', { projectId, branchId, ref }],
]);
})
.then(done)
.catch(done.fail);
);
expect(store.dispatch.mock.calls).toEqual([
['getBranchData', { projectId, branchId }],
['getMergeRequestsForBranch', { projectId, branchId }],
['getFiles', { projectId, branchId, ref }],
]);
});
it('shows an error if branch can not be fetched', (done) => {
it('shows an error if branch can not be fetched', async () => {
jest.spyOn(store, 'dispatch').mockReturnValue(Promise.reject());
loadBranch(store, { projectId, branchId })
.then(done.fail)
.catch(() => {
expect(store.dispatch.mock.calls).toEqual([
['getBranchData', { projectId, branchId }],
['showBranchNotFoundError', branchId],
]);
done();
});
await expect(loadBranch(store, { projectId, branchId })).rejects.toBeUndefined();
expect(store.dispatch.mock.calls).toEqual([
['getBranchData', { projectId, branchId }],
['showBranchNotFoundError', branchId],
]);
});
});
......@@ -449,17 +419,13 @@ describe('IDE store project actions', () => {
jest.spyOn(store, 'dispatch').mockResolvedValue();
});
it('dispatches branch actions', (done) => {
openBranch(store, branch)
.then(() => {
expect(store.dispatch.mock.calls).toEqual([
['setCurrentBranchId', branchId],
['loadBranch', { projectId, branchId }],
['loadFile', { basePath: undefined }],
]);
})
.then(done)
.catch(done.fail);
it('dispatches branch actions', async () => {
await openBranch(store, branch);
expect(store.dispatch.mock.calls).toEqual([
['setCurrentBranchId', branchId],
['loadBranch', { projectId, branchId }],
['loadFile', { basePath: undefined }],
]);
});
});
......@@ -468,22 +434,18 @@ describe('IDE store project actions', () => {
jest.spyOn(store, 'dispatch').mockReturnValue(Promise.reject());
});
it('dispatches correct branch actions', (done) => {
openBranch(store, branch)
.then((val) => {
expect(store.dispatch.mock.calls).toEqual([
['setCurrentBranchId', branchId],
['loadBranch', { projectId, branchId }],
]);
expect(val).toEqual(
new Error(
`An error occurred while getting files for - <strong>${projectId}/${branchId}</strong>`,
),
);
})
.then(done)
.catch(done.fail);
it('dispatches correct branch actions', async () => {
const val = await openBranch(store, branch);
expect(store.dispatch.mock.calls).toEqual([
['setCurrentBranchId', branchId],
['loadBranch', { projectId, branchId }],
]);
expect(val).toEqual(
new Error(
`An error occurred while getting files for - <strong>${projectId}/${branchId}</strong>`,
),
);
});
});
});
......
......@@ -62,27 +62,21 @@ describe('Multi-file store tree actions', () => {
});
});
it('adds data into tree', (done) => {
store
.dispatch('getFiles', basicCallParameters)
.then(() => {
projectTree = store.state.trees['abcproject/main'];
expect(projectTree.tree.length).toBe(2);
expect(projectTree.tree[0].type).toBe('tree');
expect(projectTree.tree[0].tree[1].name).toBe('fileinfolder.js');
expect(projectTree.tree[1].type).toBe('blob');
expect(projectTree.tree[0].tree[0].tree[0].type).toBe('blob');
expect(projectTree.tree[0].tree[0].tree[0].name).toBe('fileinsubfolder.js');
done();
})
.catch(done.fail);
it('adds data into tree', async () => {
await store.dispatch('getFiles', basicCallParameters);
projectTree = store.state.trees['abcproject/main'];
expect(projectTree.tree.length).toBe(2);
expect(projectTree.tree[0].type).toBe('tree');
expect(projectTree.tree[0].tree[1].name).toBe('fileinfolder.js');
expect(projectTree.tree[1].type).toBe('blob');
expect(projectTree.tree[0].tree[0].tree[0].type).toBe('blob');
expect(projectTree.tree[0].tree[0].tree[0].name).toBe('fileinsubfolder.js');
});
});
describe('error', () => {
it('dispatches error action', (done) => {
it('dispatches error action', async () => {
const dispatch = jest.fn();
store.state.projects = {
......@@ -103,28 +97,26 @@ describe('Multi-file store tree actions', () => {
mock.onGet(/(.*)/).replyOnce(500);
getFiles(
{
commit() {},
dispatch,
state: store.state,
getters,
},
{
projectId: 'abc/def',
branchId: 'main-testing',
},
)
.then(done.fail)
.catch(() => {
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading all the files.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: { projectId: 'abc/def', branchId: 'main-testing' },
});
done();
});
await expect(
getFiles(
{
commit() {},
dispatch,
state: store.state,
getters,
},
{
projectId: 'abc/def',
branchId: 'main-testing',
},
),
).rejects.toEqual(new Error('Request failed with status code 500'));
expect(dispatch).toHaveBeenCalledWith('setErrorMessage', {
text: 'An error occurred while loading all the files.',
action: expect.any(Function),
actionText: 'Please try again',
actionPayload: { projectId: 'abc/def', branchId: 'main-testing' },
});
});
});
});
......@@ -137,15 +129,9 @@ describe('Multi-file store tree actions', () => {
store.state.entries[tree.path] = tree;
});
it('toggles the tree open', (done) => {
store
.dispatch('toggleTreeOpen', tree.path)
.then(() => {
expect(tree.opened).toBeTruthy();
done();
})
.catch(done.fail);
it('toggles the tree open', async () => {
await store.dispatch('toggleTreeOpen', tree.path);
expect(tree.opened).toBeTruthy();
});
});
......@@ -163,24 +149,23 @@ describe('Multi-file store tree actions', () => {
Object.assign(store.state.entries, createEntriesFromPaths(paths));
});
it('opens the parents', (done) => {
testAction(
it('opens the parents', () => {
return testAction(
showTreeEntry,
'grandparent/parent/child.txt',
store.state,
[{ type: types.SET_TREE_OPEN, payload: 'grandparent/parent' }],
[{ type: 'showTreeEntry', payload: 'grandparent/parent' }],
done,
);
});
});
describe('setDirectoryData', () => {
it('sets tree correctly if there are no opened files yet', (done) => {
it('sets tree correctly if there are no opened files yet', () => {
const treeFile = file({ name: 'README.md' });
store.state.trees['abcproject/main'] = {};
testAction(
return testAction(
setDirectoryData,
{ projectId: 'abcproject', branchId: 'main', treeList: [treeFile] },
store.state,
......@@ -201,7 +186,6 @@ describe('Multi-file store tree actions', () => {
},
],
[],
done,
);
});
});
......
......@@ -43,15 +43,9 @@ describe('Multi-file store actions', () => {
});
describe('redirectToUrl', () => {
it('calls visitUrl', (done) => {
store
.dispatch('redirectToUrl', 'test')
.then(() => {
expect(visitUrl).toHaveBeenCalledWith('test');
done();
})
.catch(done.fail);
it('calls visitUrl', async () => {
await store.dispatch('redirectToUrl', 'test');
expect(visitUrl).toHaveBeenCalledWith('test');
});
});
......@@ -89,15 +83,10 @@ describe('Multi-file store actions', () => {
expect(store.dispatch.mock.calls).toEqual(expect.arrayContaining(expectedCalls));
});
it('removes all files from changedFiles state', (done) => {
store
.dispatch('discardAllChanges')
.then(() => {
expect(store.state.changedFiles.length).toBe(0);
expect(store.state.openFiles.length).toBe(2);
})
.then(done)
.catch(done.fail);
it('removes all files from changedFiles state', async () => {
await store.dispatch('discardAllChanges');
expect(store.state.changedFiles.length).toBe(0);
expect(store.state.openFiles.length).toBe(2);
});
});
......@@ -121,24 +110,18 @@ describe('Multi-file store actions', () => {
});
describe('tree', () => {
it('creates temp tree', (done) => {
store
.dispatch('createTempEntry', {
name: 'test',
type: 'tree',
})
.then(() => {
const entry = store.state.entries.test;
expect(entry).not.toBeNull();
expect(entry.type).toBe('tree');
it('creates temp tree', async () => {
await store.dispatch('createTempEntry', {
name: 'test',
type: 'tree',
});
const entry = store.state.entries.test;
done();
})
.catch(done.fail);
expect(entry).not.toBeNull();
expect(entry.type).toBe('tree');
});
it('creates new folder inside another tree', (done) => {
it('creates new folder inside another tree', async () => {
const tree = {
type: 'tree',
name: 'testing',
......@@ -148,22 +131,16 @@ describe('Multi-file store actions', () => {
store.state.entries[tree.path] = tree;
store
.dispatch('createTempEntry', {
name: 'testing/test',
type: 'tree',
})
.then(() => {
expect(tree.tree[0].tempFile).toBeTruthy();
expect(tree.tree[0].name).toBe('test');
expect(tree.tree[0].type).toBe('tree');
done();
})
.catch(done.fail);
await store.dispatch('createTempEntry', {
name: 'testing/test',
type: 'tree',
});
expect(tree.tree[0].tempFile).toBeTruthy();
expect(tree.tree[0].name).toBe('test');
expect(tree.tree[0].type).toBe('tree');
});
it('does not create new tree if already exists', (done) => {
it('does not create new tree if already exists', async () => {
const tree = {
type: 'tree',
path: 'testing',
......@@ -173,76 +150,52 @@ describe('Multi-file store actions', () => {
store.state.entries[tree.path] = tree;
store
.dispatch('createTempEntry', {
name: 'testing',
type: 'tree',
})
.then(() => {
expect(store.state.entries[tree.path].tempFile).toEqual(false);
expect(document.querySelector('.flash-alert')).not.toBeNull();
done();
})
.catch(done.fail);
await store.dispatch('createTempEntry', {
name: 'testing',
type: 'tree',
});
expect(store.state.entries[tree.path].tempFile).toEqual(false);
expect(document.querySelector('.flash-alert')).not.toBeNull();
});
});
describe('blob', () => {
it('creates temp file', (done) => {
it('creates temp file', async () => {
const name = 'test';
store
.dispatch('createTempEntry', {
name,
type: 'blob',
mimeType: 'test/mime',
})
.then(() => {
const f = store.state.entries[name];
expect(f.tempFile).toBeTruthy();
expect(f.mimeType).toBe('test/mime');
expect(store.state.trees['abcproject/mybranch'].tree.length).toBe(1);
done();
})
.catch(done.fail);
await store.dispatch('createTempEntry', {
name,
type: 'blob',
mimeType: 'test/mime',
});
const f = store.state.entries[name];
expect(f.tempFile).toBeTruthy();
expect(f.mimeType).toBe('test/mime');
expect(store.state.trees['abcproject/mybranch'].tree.length).toBe(1);
});
it('adds tmp file to open files', (done) => {
it('adds tmp file to open files', async () => {
const name = 'test';
store
.dispatch('createTempEntry', {
name,
type: 'blob',
})
.then(() => {
const f = store.state.entries[name];
expect(store.state.openFiles.length).toBe(1);
expect(store.state.openFiles[0].name).toBe(f.name);
await store.dispatch('createTempEntry', {
name,
type: 'blob',
});
const f = store.state.entries[name];
done();
})
.catch(done.fail);
expect(store.state.openFiles.length).toBe(1);
expect(store.state.openFiles[0].name).toBe(f.name);
});
it('adds tmp file to staged files', (done) => {
it('adds tmp file to staged files', async () => {
const name = 'test';
store
.dispatch('createTempEntry', {
name,
type: 'blob',
})
.then(() => {
expect(store.state.stagedFiles).toEqual([expect.objectContaining({ name })]);
done();
})
.catch(done.fail);
await store.dispatch('createTempEntry', {
name,
type: 'blob',
});
expect(store.state.stagedFiles).toEqual([expect.objectContaining({ name })]);
});
it('sets tmp file as active', () => {
......@@ -251,24 +204,18 @@ describe('Multi-file store actions', () => {
expect(store.dispatch).toHaveBeenCalledWith('setFileActive', 'test');
});
it('creates flash message if file already exists', (done) => {
it('creates flash message if file already exists', async () => {
const f = file('test', '1', 'blob');
store.state.trees['abcproject/mybranch'].tree = [f];
store.state.entries[f.path] = f;
store
.dispatch('createTempEntry', {
name: 'test',
type: 'blob',
})
.then(() => {
expect(document.querySelector('.flash-alert')?.textContent.trim()).toEqual(
`The name "${f.name}" is already taken in this directory.`,
);
done();
})
.catch(done.fail);
await store.dispatch('createTempEntry', {
name: 'test',
type: 'blob',
});
expect(document.querySelector('.flash-alert')?.textContent.trim()).toEqual(
`The name "${f.name}" is already taken in this directory.`,
);
});
});
});
......@@ -372,45 +319,38 @@ describe('Multi-file store actions', () => {
});
describe('updateViewer', () => {
it('updates viewer state', (done) => {
store
.dispatch('updateViewer', 'diff')
.then(() => {
expect(store.state.viewer).toBe('diff');
})
.then(done)
.catch(done.fail);
it('updates viewer state', async () => {
await store.dispatch('updateViewer', 'diff');
expect(store.state.viewer).toBe('diff');
});
});
describe('updateActivityBarView', () => {
it('commits UPDATE_ACTIVITY_BAR_VIEW', (done) => {
testAction(
it('commits UPDATE_ACTIVITY_BAR_VIEW', () => {
return testAction(
updateActivityBarView,
'test',
{},
[{ type: 'UPDATE_ACTIVITY_BAR_VIEW', payload: 'test' }],
[],
done,
);
});
});
describe('setEmptyStateSvgs', () => {
it('commits setEmptyStateSvgs', (done) => {
testAction(
it('commits setEmptyStateSvgs', () => {
return testAction(
setEmptyStateSvgs,
'svg',
{},
[{ type: 'SET_EMPTY_STATE_SVGS', payload: 'svg' }],
[],
done,
);
});
});
describe('updateTempFlagForEntry', () => {
it('commits UPDATE_TEMP_FLAG', (done) => {
it('commits UPDATE_TEMP_FLAG', () => {
const f = {
...file(),
path: 'test',
......@@ -418,17 +358,16 @@ describe('Multi-file store actions', () => {
};
store.state.entries[f.path] = f;
testAction(
return testAction(
updateTempFlagForEntry,
{ file: f, tempFile: false },
store.state,
[{ type: 'UPDATE_TEMP_FLAG', payload: { path: f.path, tempFile: false } }],
[],
done,
);
});
it('commits UPDATE_TEMP_FLAG and dispatches for parent', (done) => {
it('commits UPDATE_TEMP_FLAG and dispatches for parent', () => {
const parent = {
...file(),
path: 'testing',
......@@ -441,17 +380,16 @@ describe('Multi-file store actions', () => {
store.state.entries[parent.path] = parent;
store.state.entries[f.path] = f;
testAction(
return testAction(
updateTempFlagForEntry,
{ file: f, tempFile: false },
store.state,
[{ type: 'UPDATE_TEMP_FLAG', payload: { path: f.path, tempFile: false } }],
[{ type: 'updateTempFlagForEntry', payload: { file: parent, tempFile: false } }],
done,
);
});
it('does not dispatch for parent, if parent does not exist', (done) => {
it('does not dispatch for parent, if parent does not exist', () => {
const f = {
...file(),
path: 'test',
......@@ -459,71 +397,66 @@ describe('Multi-file store actions', () => {
};
store.state.entries[f.path] = f;
testAction(
return testAction(
updateTempFlagForEntry,
{ file: f, tempFile: false },
store.state,
[{ type: 'UPDATE_TEMP_FLAG', payload: { path: f.path, tempFile: false } }],
[],
done,
);
});
});
describe('setCurrentBranchId', () => {
it('commits setCurrentBranchId', (done) => {
testAction(
it('commits setCurrentBranchId', () => {
return testAction(
setCurrentBranchId,
'branchId',
{},
[{ type: 'SET_CURRENT_BRANCH', payload: 'branchId' }],
[],
done,
);
});
});
describe('toggleFileFinder', () => {
it('commits TOGGLE_FILE_FINDER', (done) => {
testAction(
it('commits TOGGLE_FILE_FINDER', () => {
return testAction(
toggleFileFinder,
true,
null,
[{ type: 'TOGGLE_FILE_FINDER', payload: true }],
[],
done,
);
});
});
describe('setErrorMessage', () => {
it('commis error messsage', (done) => {
testAction(
it('commis error messsage', () => {
return testAction(
setErrorMessage,
'error',
null,
[{ type: types.SET_ERROR_MESSAGE, payload: 'error' }],
[],
done,
);
});
});
describe('deleteEntry', () => {
it('commits entry deletion', (done) => {
it('commits entry deletion', () => {
store.state.entries.path = 'testing';
testAction(
return testAction(
deleteEntry,
'path',
store.state,
[{ type: types.DELETE_ENTRY, payload: 'path' }],
[{ type: 'stageChange', payload: 'path' }, createTriggerChangeAction()],
done,
);
});
it('does not delete a folder after it is emptied', (done) => {
it('does not delete a folder after it is emptied', () => {
const testFolder = {
type: 'tree',
tree: [],
......@@ -540,7 +473,7 @@ describe('Multi-file store actions', () => {
'testFolder/entry-to-delete': testEntry,
};
testAction(
return testAction(
deleteEntry,
'testFolder/entry-to-delete',
store.state,
......@@ -549,7 +482,6 @@ describe('Multi-file store actions', () => {
{ type: 'stageChange', payload: 'testFolder/entry-to-delete' },
createTriggerChangeAction(),
],
done,
);
});
......@@ -569,8 +501,8 @@ describe('Multi-file store actions', () => {
});
describe('and previous does not exist', () => {
it('reverts the rename before deleting', (done) => {
testAction(
it('reverts the rename before deleting', () => {
return testAction(
deleteEntry,
testEntry.path,
store.state,
......@@ -589,7 +521,6 @@ describe('Multi-file store actions', () => {
payload: testEntry.prevPath,
},
],
done,
);
});
});
......@@ -604,21 +535,20 @@ describe('Multi-file store actions', () => {
store.state.entries[oldEntry.path] = oldEntry;
});
it('does not revert rename before deleting', (done) => {
testAction(
it('does not revert rename before deleting', () => {
return testAction(
deleteEntry,
testEntry.path,
store.state,
[{ type: types.DELETE_ENTRY, payload: testEntry.path }],
[{ type: 'stageChange', payload: testEntry.path }, createTriggerChangeAction()],
done,
);
});
it('when previous is deleted, it reverts rename before deleting', (done) => {
it('when previous is deleted, it reverts rename before deleting', () => {
store.state.entries[testEntry.prevPath].deleted = true;
testAction(
return testAction(
deleteEntry,
testEntry.path,
store.state,
......@@ -637,7 +567,6 @@ describe('Multi-file store actions', () => {
payload: testEntry.prevPath,
},
],
done,
);
});
});
......@@ -650,7 +579,7 @@ describe('Multi-file store actions', () => {
jest.spyOn(eventHub, '$emit').mockImplementation();
});
it('does not purge model cache for temporary entries that got renamed', (done) => {
it('does not purge model cache for temporary entries that got renamed', async () => {
Object.assign(store.state.entries, {
test: {
...file('test'),
......@@ -660,19 +589,14 @@ describe('Multi-file store actions', () => {
},
});
store
.dispatch('renameEntry', {
path: 'test',
name: 'new',
})
.then(() => {
expect(eventHub.$emit.mock.calls).not.toContain('editor.update.model.dispose.foo-bar');
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: 'test',
name: 'new',
});
expect(eventHub.$emit.mock.calls).not.toContain('editor.update.model.dispose.foo-bar');
});
it('purges model cache for renamed entry', (done) => {
it('purges model cache for renamed entry', async () => {
Object.assign(store.state.entries, {
test: {
...file('test'),
......@@ -682,17 +606,12 @@ describe('Multi-file store actions', () => {
},
});
store
.dispatch('renameEntry', {
path: 'test',
name: 'new',
})
.then(() => {
expect(eventHub.$emit).toHaveBeenCalled();
expect(eventHub.$emit).toHaveBeenCalledWith(`editor.update.model.dispose.foo-key`);
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: 'test',
name: 'new',
});
expect(eventHub.$emit).toHaveBeenCalled();
expect(eventHub.$emit).toHaveBeenCalledWith(`editor.update.model.dispose.foo-key`);
});
});
......@@ -731,8 +650,8 @@ describe('Multi-file store actions', () => {
]);
});
it('if not changed, completely unstages and discards entry if renamed to original', (done) => {
testAction(
it('if not changed, completely unstages and discards entry if renamed to original', () => {
return testAction(
renameEntry,
{ path: 'renamed', name: 'orig' },
store.state,
......@@ -751,24 +670,22 @@ describe('Multi-file store actions', () => {
},
],
[createTriggerRenameAction('renamed', 'orig')],
done,
);
});
it('if already in changed, does not add to change', (done) => {
it('if already in changed, does not add to change', () => {
store.state.changedFiles.push(renamedEntry);
testAction(
return testAction(
renameEntry,
{ path: 'orig', name: 'renamed' },
store.state,
[expect.objectContaining({ type: types.RENAME_ENTRY })],
[createTriggerRenameAction('orig', 'renamed')],
done,
);
});
it('routes to the renamed file if the original file has been opened', (done) => {
it('routes to the renamed file if the original file has been opened', async () => {
store.state.currentProjectId = 'test/test';
store.state.currentBranchId = 'main';
......@@ -776,17 +693,12 @@ describe('Multi-file store actions', () => {
opened: true,
});
store
.dispatch('renameEntry', {
path: 'orig',
name: 'renamed',
})
.then(() => {
expect(router.push.mock.calls).toHaveLength(1);
expect(router.push).toHaveBeenCalledWith(`/project/test/test/tree/main/-/renamed/`);
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: 'orig',
name: 'renamed',
});
expect(router.push.mock.calls).toHaveLength(1);
expect(router.push).toHaveBeenCalledWith(`/project/test/test/tree/main/-/renamed/`);
});
});
......@@ -809,25 +721,20 @@ describe('Multi-file store actions', () => {
});
});
it('updates entries in a folder correctly, when folder is renamed', (done) => {
store
.dispatch('renameEntry', {
path: 'folder',
name: 'new-folder',
})
.then(() => {
const keys = Object.keys(store.state.entries);
expect(keys.length).toBe(3);
expect(keys.indexOf('new-folder')).toBe(0);
expect(keys.indexOf('new-folder/file-1')).toBe(1);
expect(keys.indexOf('new-folder/file-2')).toBe(2);
})
.then(done)
.catch(done.fail);
it('updates entries in a folder correctly, when folder is renamed', async () => {
await store.dispatch('renameEntry', {
path: 'folder',
name: 'new-folder',
});
const keys = Object.keys(store.state.entries);
expect(keys.length).toBe(3);
expect(keys.indexOf('new-folder')).toBe(0);
expect(keys.indexOf('new-folder/file-1')).toBe(1);
expect(keys.indexOf('new-folder/file-2')).toBe(2);
});
it('discards renaming of an entry if the root folder is renamed back to a previous name', (done) => {
it('discards renaming of an entry if the root folder is renamed back to a previous name', async () => {
const rootFolder = file('old-folder', 'old-folder', 'tree');
const testEntry = file('test', 'test', 'blob', rootFolder);
......@@ -841,53 +748,45 @@ describe('Multi-file store actions', () => {
},
});
store
.dispatch('renameEntry', {
path: 'old-folder',
name: 'new-folder',
})
.then(() => {
const { entries } = store.state;
expect(Object.keys(entries).length).toBe(2);
expect(entries['old-folder']).toBeUndefined();
expect(entries['old-folder/test']).toBeUndefined();
expect(entries['new-folder']).toBeDefined();
expect(entries['new-folder/test']).toEqual(
expect.objectContaining({
path: 'new-folder/test',
name: 'test',
prevPath: 'old-folder/test',
prevName: 'test',
}),
);
})
.then(() =>
store.dispatch('renameEntry', {
path: 'new-folder',
name: 'old-folder',
}),
)
.then(() => {
const { entries } = store.state;
expect(Object.keys(entries).length).toBe(2);
expect(entries['new-folder']).toBeUndefined();
expect(entries['new-folder/test']).toBeUndefined();
expect(entries['old-folder']).toBeDefined();
expect(entries['old-folder/test']).toEqual(
expect.objectContaining({
path: 'old-folder/test',
name: 'test',
prevPath: undefined,
prevName: undefined,
}),
);
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: 'old-folder',
name: 'new-folder',
});
const { entries } = store.state;
expect(Object.keys(entries).length).toBe(2);
expect(entries['old-folder']).toBeUndefined();
expect(entries['old-folder/test']).toBeUndefined();
expect(entries['new-folder']).toBeDefined();
expect(entries['new-folder/test']).toEqual(
expect.objectContaining({
path: 'new-folder/test',
name: 'test',
prevPath: 'old-folder/test',
prevName: 'test',
}),
);
await store.dispatch('renameEntry', {
path: 'new-folder',
name: 'old-folder',
});
const { entries: newEntries } = store.state;
expect(Object.keys(newEntries).length).toBe(2);
expect(newEntries['new-folder']).toBeUndefined();
expect(newEntries['new-folder/test']).toBeUndefined();
expect(newEntries['old-folder']).toBeDefined();
expect(newEntries['old-folder/test']).toEqual(
expect.objectContaining({
path: 'old-folder/test',
name: 'test',
prevPath: undefined,
prevName: undefined,
}),
);
});
describe('with file in directory', () => {
......@@ -919,24 +818,21 @@ describe('Multi-file store actions', () => {
});
});
it('creates new directory', (done) => {
it('creates new directory', async () => {
expect(store.state.entries[newParentPath]).toBeUndefined();
store
.dispatch('renameEntry', { path: filePath, name: fileName, parentPath: newParentPath })
.then(() => {
expect(store.state.entries[newParentPath]).toEqual(
expect.objectContaining({
path: newParentPath,
type: 'tree',
tree: expect.arrayContaining([
store.state.entries[`${newParentPath}/${fileName}`],
]),
}),
);
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: filePath,
name: fileName,
parentPath: newParentPath,
});
expect(store.state.entries[newParentPath]).toEqual(
expect.objectContaining({
path: newParentPath,
type: 'tree',
tree: expect.arrayContaining([store.state.entries[`${newParentPath}/${fileName}`]]),
}),
);
});
describe('when new directory exists', () => {
......@@ -949,40 +845,30 @@ describe('Multi-file store actions', () => {
rootDir.tree.push(newDir);
});
it('inserts in new directory', (done) => {
it('inserts in new directory', async () => {
expect(newDir.tree).toEqual([]);
store
.dispatch('renameEntry', {
path: filePath,
name: fileName,
parentPath: newParentPath,
})
.then(() => {
expect(newDir.tree).toEqual([store.state.entries[`${newParentPath}/${fileName}`]]);
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: filePath,
name: fileName,
parentPath: newParentPath,
});
expect(newDir.tree).toEqual([store.state.entries[`${newParentPath}/${fileName}`]]);
});
it('when new directory is deleted, it undeletes it', (done) => {
store.dispatch('deleteEntry', newParentPath);
it('when new directory is deleted, it undeletes it', async () => {
await store.dispatch('deleteEntry', newParentPath);
expect(store.state.entries[newParentPath].deleted).toBe(true);
expect(rootDir.tree.some((x) => x.path === newParentPath)).toBe(false);
store
.dispatch('renameEntry', {
path: filePath,
name: fileName,
parentPath: newParentPath,
})
.then(() => {
expect(store.state.entries[newParentPath].deleted).toBe(false);
expect(rootDir.tree.some((x) => x.path === newParentPath)).toBe(true);
})
.then(done)
.catch(done.fail);
await store.dispatch('renameEntry', {
path: filePath,
name: fileName,
parentPath: newParentPath,
});
expect(store.state.entries[newParentPath].deleted).toBe(false);
expect(rootDir.tree.some((x) => x.path === newParentPath)).toBe(true);
});
});
});
......@@ -1023,30 +909,25 @@ describe('Multi-file store actions', () => {
document.querySelector('.flash-container').remove();
});
it('passes the error further unchanged without dispatching any action when response is 404', (done) => {
it('passes the error further unchanged without dispatching any action when response is 404', async () => {
mock.onGet(/(.*)/).replyOnce(404);
getBranchData(...callParams)
.then(done.fail)
.catch((e) => {
expect(dispatch.mock.calls).toHaveLength(0);
expect(e.response.status).toEqual(404);
expect(document.querySelector('.flash-alert')).toBeNull();
done();
});
await expect(getBranchData(...callParams)).rejects.toEqual(
new Error('Request failed with status code 404'),
);
expect(dispatch.mock.calls).toHaveLength(0);
expect(document.querySelector('.flash-alert')).toBeNull();
});
it('does not pass the error further and flashes an alert if error is not 404', (done) => {
it('does not pass the error further and flashes an alert if error is not 404', async () => {
mock.onGet(/(.*)/).replyOnce(418);
getBranchData(...callParams)
.then(done.fail)
.catch((e) => {
expect(dispatch.mock.calls).toHaveLength(0);
expect(e.response).toBeUndefined();
expect(document.querySelector('.flash-alert')).not.toBeNull();
done();
});
await expect(getBranchData(...callParams)).rejects.toEqual(
new Error('Branch not loaded - <strong>abc/def/main-testing</strong>'),
);
expect(dispatch.mock.calls).toHaveLength(0);
expect(document.querySelector('.flash-alert')).not.toBeNull();
});
});
});
......
......@@ -42,21 +42,20 @@ describe('IDE branches actions', () => {
});
describe('requestBranches', () => {
it('should commit request', (done) => {
testAction(
it('should commit request', () => {
return testAction(
requestBranches,
null,
mockedContext.state,
[{ type: types.REQUEST_BRANCHES }],
[],
done,
);
});
});
describe('receiveBranchesError', () => {
it('should commit error', (done) => {
testAction(
it('should commit error', () => {
return testAction(
receiveBranchesError,
{ search: TEST_SEARCH },
mockedContext.state,
......@@ -72,20 +71,18 @@ describe('IDE branches actions', () => {
},
},
],
done,
);
});
});
describe('receiveBranchesSuccess', () => {
it('should commit received data', (done) => {
testAction(
it('should commit received data', () => {
return testAction(
receiveBranchesSuccess,
branches,
mockedContext.state,
[{ type: types.RECEIVE_BRANCHES_SUCCESS, payload: branches }],
[],
done,
);
});
});
......@@ -110,8 +107,8 @@ describe('IDE branches actions', () => {
});
});
it('dispatches success with received data', (done) => {
testAction(
it('dispatches success with received data', () => {
return testAction(
fetchBranches,
{ search: TEST_SEARCH },
mockedState,
......@@ -121,7 +118,6 @@ describe('IDE branches actions', () => {
{ type: 'resetBranches' },
{ type: 'receiveBranchesSuccess', payload: branches },
],
done,
);
});
});
......@@ -131,8 +127,8 @@ describe('IDE branches actions', () => {
mock.onGet(/\/api\/v4\/projects\/\d+\/repository\/branches(.*)$/).replyOnce(500);
});
it('dispatches error', (done) => {
testAction(
it('dispatches error', () => {
return testAction(
fetchBranches,
{ search: TEST_SEARCH },
mockedState,
......@@ -142,20 +138,18 @@ describe('IDE branches actions', () => {
{ type: 'resetBranches' },
{ type: 'receiveBranchesError', payload: { search: TEST_SEARCH } },
],
done,
);
});
});
describe('resetBranches', () => {
it('commits reset', (done) => {
testAction(
it('commits reset', () => {
return testAction(
resetBranches,
null,
mockedContext.state,
[{ type: types.RESET_BRANCHES }],
[],
done,
);
});
});
......
......@@ -26,15 +26,13 @@ describe('IDE store module clientside actions', () => {
});
describe('pingUsage', () => {
it('posts to usage endpoint', (done) => {
it('posts to usage endpoint', async () => {
const usageSpy = jest.fn(() => [200]);
mock.onPost(TEST_USAGE_URL).reply(() => usageSpy());
testAction(actions.pingUsage, PING_USAGE_PREVIEW_KEY, rootGetters, [], [], () => {
expect(usageSpy).toHaveBeenCalled();
done();
});
await testAction(actions.pingUsage, PING_USAGE_PREVIEW_KEY, rootGetters, [], []);
expect(usageSpy).toHaveBeenCalled();
});
});
});
......@@ -57,40 +57,25 @@ describe('IDE commit module actions', () => {
});
describe('updateCommitMessage', () => {
it('updates store with new commit message', (done) => {
store
.dispatch('commit/updateCommitMessage', 'testing')
.then(() => {
expect(store.state.commit.commitMessage).toBe('testing');
})
.then(done)
.catch(done.fail);
it('updates store with new commit message', async () => {
await store.dispatch('commit/updateCommitMessage', 'testing');
expect(store.state.commit.commitMessage).toBe('testing');
});
});
describe('discardDraft', () => {
it('resets commit message to blank', (done) => {
it('resets commit message to blank', async () => {
store.state.commit.commitMessage = 'testing';
store
.dispatch('commit/discardDraft')
.then(() => {
expect(store.state.commit.commitMessage).not.toBe('testing');
})
.then(done)
.catch(done.fail);
await store.dispatch('commit/discardDraft');
expect(store.state.commit.commitMessage).not.toBe('testing');
});
});
describe('updateCommitAction', () => {
it('updates store with new commit action', (done) => {
store
.dispatch('commit/updateCommitAction', '1')
.then(() => {
expect(store.state.commit.commitAction).toBe('1');
})
.then(done)
.catch(done.fail);
it('updates store with new commit action', async () => {
await store.dispatch('commit/updateCommitAction', '1');
expect(store.state.commit.commitAction).toBe('1');
});
});
......@@ -139,34 +124,24 @@ describe('IDE commit module actions', () => {
});
});
it('updates commit message with short_id', (done) => {
store
.dispatch('commit/setLastCommitMessage', { short_id: '123' })
.then(() => {
expect(store.state.lastCommitMsg).toContain(
'Your changes have been committed. Commit <a href="http://testing/-/commit/123" class="commit-sha">123</a>',
);
})
.then(done)
.catch(done.fail);
it('updates commit message with short_id', async () => {
await store.dispatch('commit/setLastCommitMessage', { short_id: '123' });
expect(store.state.lastCommitMsg).toContain(
'Your changes have been committed. Commit <a href="http://testing/-/commit/123" class="commit-sha">123</a>',
);
});
it('updates commit message with stats', (done) => {
store
.dispatch('commit/setLastCommitMessage', {
short_id: '123',
stats: {
additions: '1',
deletions: '2',
},
})
.then(() => {
expect(store.state.lastCommitMsg).toBe(
'Your changes have been committed. Commit <a href="http://testing/-/commit/123" class="commit-sha">123</a> with 1 additions, 2 deletions.',
);
})
.then(done)
.catch(done.fail);
it('updates commit message with stats', async () => {
await store.dispatch('commit/setLastCommitMessage', {
short_id: '123',
stats: {
additions: '1',
deletions: '2',
},
});
expect(store.state.lastCommitMsg).toBe(
'Your changes have been committed. Commit <a href="http://testing/-/commit/123" class="commit-sha">123</a> with 1 additions, 2 deletions.',
);
});
});
......@@ -221,74 +196,49 @@ describe('IDE commit module actions', () => {
});
});
it('updates stores working reference', (done) => {
store
.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
})
.then(() => {
expect(store.state.projects.abcproject.branches.main.workingReference).toBe(data.id);
})
.then(done)
.catch(done.fail);
it('updates stores working reference', async () => {
await store.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
});
expect(store.state.projects.abcproject.branches.main.workingReference).toBe(data.id);
});
it('resets all files changed status', (done) => {
store
.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
})
.then(() => {
store.state.openFiles.forEach((entry) => {
expect(entry.changed).toBeFalsy();
});
})
.then(done)
.catch(done.fail);
it('resets all files changed status', async () => {
await store.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
});
store.state.openFiles.forEach((entry) => {
expect(entry.changed).toBeFalsy();
});
});
it('sets files commit data', (done) => {
store
.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
})
.then(() => {
expect(f.lastCommitSha).toBe(data.id);
})
.then(done)
.catch(done.fail);
it('sets files commit data', async () => {
await store.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
});
expect(f.lastCommitSha).toBe(data.id);
});
it('updates raw content for changed file', (done) => {
store
.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
})
.then(() => {
expect(f.raw).toBe(f.content);
})
.then(done)
.catch(done.fail);
it('updates raw content for changed file', async () => {
await store.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
});
expect(f.raw).toBe(f.content);
});
it('emits changed event for file', (done) => {
store
.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
})
.then(() => {
expect(eventHub.$emit).toHaveBeenCalledWith(`editor.update.model.content.${f.key}`, {
content: f.content,
changed: false,
});
})
.then(done)
.catch(done.fail);
it('emits changed event for file', async () => {
await store.dispatch('commit/updateFilesAfterCommit', {
data,
branch,
});
expect(eventHub.$emit).toHaveBeenCalledWith(`editor.update.model.content.${f.key}`, {
content: f.content,
changed: false,
});
});
});
......@@ -349,138 +299,93 @@ describe('IDE commit module actions', () => {
jest.spyOn(service, 'commit').mockResolvedValue({ data: COMMIT_RESPONSE });
});
it('calls service', (done) => {
store
.dispatch('commit/commitChanges')
.then(() => {
expect(service.commit).toHaveBeenCalledWith('abcproject', {
branch: expect.anything(),
commit_message: 'testing 123',
actions: [
{
action: commitActionTypes.update,
file_path: expect.anything(),
content: '\n',
encoding: expect.anything(),
last_commit_id: undefined,
previous_path: undefined,
},
],
start_sha: TEST_COMMIT_SHA,
});
done();
})
.catch(done.fail);
it('calls service', async () => {
await store.dispatch('commit/commitChanges');
expect(service.commit).toHaveBeenCalledWith('abcproject', {
branch: expect.anything(),
commit_message: 'testing 123',
actions: [
{
action: commitActionTypes.update,
file_path: expect.anything(),
content: '\n',
encoding: expect.anything(),
last_commit_id: undefined,
previous_path: undefined,
},
],
start_sha: TEST_COMMIT_SHA,
});
});
it('sends lastCommit ID when not creating new branch', (done) => {
it('sends lastCommit ID when not creating new branch', async () => {
store.state.commit.commitAction = '1';
store
.dispatch('commit/commitChanges')
.then(() => {
expect(service.commit).toHaveBeenCalledWith('abcproject', {
branch: expect.anything(),
commit_message: 'testing 123',
actions: [
{
action: commitActionTypes.update,
file_path: expect.anything(),
content: '\n',
encoding: expect.anything(),
last_commit_id: TEST_COMMIT_SHA,
previous_path: undefined,
},
],
start_sha: undefined,
});
done();
})
.catch(done.fail);
await store.dispatch('commit/commitChanges');
expect(service.commit).toHaveBeenCalledWith('abcproject', {
branch: expect.anything(),
commit_message: 'testing 123',
actions: [
{
action: commitActionTypes.update,
file_path: expect.anything(),
content: '\n',
encoding: expect.anything(),
last_commit_id: TEST_COMMIT_SHA,
previous_path: undefined,
},
],
start_sha: undefined,
});
});
it('sets last Commit Msg', (done) => {
store
.dispatch('commit/commitChanges')
.then(() => {
expect(store.state.lastCommitMsg).toBe(
'Your changes have been committed. Commit <a href="webUrl/-/commit/123" class="commit-sha">123</a> with 1 additions, 2 deletions.',
);
done();
})
.catch(done.fail);
it('sets last Commit Msg', async () => {
await store.dispatch('commit/commitChanges');
expect(store.state.lastCommitMsg).toBe(
'Your changes have been committed. Commit <a href="webUrl/-/commit/123" class="commit-sha">123</a> with 1 additions, 2 deletions.',
);
});
it('adds commit data to files', (done) => {
store
.dispatch('commit/commitChanges')
.then(() => {
expect(store.state.entries[store.state.openFiles[0].path].lastCommitSha).toBe(
COMMIT_RESPONSE.id,
);
done();
})
.catch(done.fail);
it('adds commit data to files', async () => {
await store.dispatch('commit/commitChanges');
expect(store.state.entries[store.state.openFiles[0].path].lastCommitSha).toBe(
COMMIT_RESPONSE.id,
);
});
it('resets stores commit actions', (done) => {
it('resets stores commit actions', async () => {
store.state.commit.commitAction = COMMIT_TO_NEW_BRANCH;
store
.dispatch('commit/commitChanges')
.then(() => {
expect(store.state.commit.commitAction).not.toBe(COMMIT_TO_NEW_BRANCH);
})
.then(done)
.catch(done.fail);
await store.dispatch('commit/commitChanges');
expect(store.state.commit.commitAction).not.toBe(COMMIT_TO_NEW_BRANCH);
});
it('removes all staged files', (done) => {
store
.dispatch('commit/commitChanges')
.then(() => {
expect(store.state.stagedFiles.length).toBe(0);
})
.then(done)
.catch(done.fail);
it('removes all staged files', async () => {
await store.dispatch('commit/commitChanges');
expect(store.state.stagedFiles.length).toBe(0);
});
describe('merge request', () => {
it('redirects to new merge request page', (done) => {
it('redirects to new merge request page', async () => {
jest.spyOn(eventHub, '$on').mockImplementation();
store.state.commit.commitAction = COMMIT_TO_NEW_BRANCH;
store.state.commit.shouldCreateMR = true;
store
.dispatch('commit/commitChanges')
.then(() => {
expect(visitUrl).toHaveBeenCalledWith(
`webUrl/-/merge_requests/new?merge_request[source_branch]=${store.getters['commit/placeholderBranchName']}&merge_request[target_branch]=main&nav_source=webide`,
);
done();
})
.catch(done.fail);
await store.dispatch('commit/commitChanges');
expect(visitUrl).toHaveBeenCalledWith(
`webUrl/-/merge_requests/new?merge_request[source_branch]=${store.getters['commit/placeholderBranchName']}&merge_request[target_branch]=main&nav_source=webide`,
);
});
it('does not redirect to new merge request page when shouldCreateMR is not checked', (done) => {
it('does not redirect to new merge request page when shouldCreateMR is not checked', async () => {
jest.spyOn(eventHub, '$on').mockImplementation();
store.state.commit.commitAction = COMMIT_TO_NEW_BRANCH;
store.state.commit.shouldCreateMR = false;
store
.dispatch('commit/commitChanges')
.then(() => {
expect(visitUrl).not.toHaveBeenCalled();
done();
})
.catch(done.fail);
await store.dispatch('commit/commitChanges');
expect(visitUrl).not.toHaveBeenCalled();
});
it('does not redirect to merge request page if shouldCreateMR is checked, but branch is the default branch', async () => {
......@@ -514,17 +419,11 @@ describe('IDE commit module actions', () => {
});
});
it('shows failed message', (done) => {
store
.dispatch('commit/commitChanges')
.then(() => {
const alert = document.querySelector('.flash-container');
expect(alert.textContent.trim()).toBe('failed message');
it('shows failed message', async () => {
await store.dispatch('commit/commitChanges');
const alert = document.querySelector('.flash-container');
done();
})
.catch(done.fail);
expect(alert.textContent.trim()).toBe('failed message');
});
});
......@@ -548,52 +447,37 @@ describe('IDE commit module actions', () => {
});
describe('first commit of a branch', () => {
it('commits TOGGLE_EMPTY_STATE mutation on empty repo', (done) => {
it('commits TOGGLE_EMPTY_STATE mutation on empty repo', async () => {
jest.spyOn(service, 'commit').mockResolvedValue({ data: COMMIT_RESPONSE });
jest.spyOn(store, 'commit');
store
.dispatch('commit/commitChanges')
.then(() => {
expect(store.commit.mock.calls).toEqual(
expect.arrayContaining([
['TOGGLE_EMPTY_STATE', expect.any(Object), expect.any(Object)],
]),
);
done();
})
.catch(done.fail);
await store.dispatch('commit/commitChanges');
expect(store.commit.mock.calls).toEqual(
expect.arrayContaining([['TOGGLE_EMPTY_STATE', expect.any(Object), expect.any(Object)]]),
);
});
it('does not commmit TOGGLE_EMPTY_STATE mutation on existing project', (done) => {
it('does not commmit TOGGLE_EMPTY_STATE mutation on existing project', async () => {
COMMIT_RESPONSE.parent_ids.push('1234');
jest.spyOn(service, 'commit').mockResolvedValue({ data: COMMIT_RESPONSE });
jest.spyOn(store, 'commit');
store
.dispatch('commit/commitChanges')
.then(() => {
expect(store.commit.mock.calls).not.toEqual(
expect.arrayContaining([
['TOGGLE_EMPTY_STATE', expect.any(Object), expect.any(Object)],
]),
);
done();
})
.catch(done.fail);
await store.dispatch('commit/commitChanges');
expect(store.commit.mock.calls).not.toEqual(
expect.arrayContaining([['TOGGLE_EMPTY_STATE', expect.any(Object), expect.any(Object)]]),
);
});
});
});
describe('toggleShouldCreateMR', () => {
it('commits both toggle and interacting with MR checkbox actions', (done) => {
testAction(
it('commits both toggle and interacting with MR checkbox actions', () => {
return testAction(
actions.toggleShouldCreateMR,
{},
store.state,
[{ type: mutationTypes.TOGGLE_SHOULD_CREATE_MR }],
[],
done,
);
});
});
......
......@@ -20,21 +20,20 @@ describe('IDE file templates actions', () => {
});
describe('requestTemplateTypes', () => {
it('commits REQUEST_TEMPLATE_TYPES', (done) => {
testAction(
it('commits REQUEST_TEMPLATE_TYPES', () => {
return testAction(
actions.requestTemplateTypes,
null,
state,
[{ type: types.REQUEST_TEMPLATE_TYPES }],
[],
done,
);
});
});
describe('receiveTemplateTypesError', () => {
it('commits RECEIVE_TEMPLATE_TYPES_ERROR and dispatches setErrorMessage', (done) => {
testAction(
it('commits RECEIVE_TEMPLATE_TYPES_ERROR and dispatches setErrorMessage', () => {
return testAction(
actions.receiveTemplateTypesError,
null,
state,
......@@ -49,20 +48,18 @@ describe('IDE file templates actions', () => {
},
},
],
done,
);
});
});
describe('receiveTemplateTypesSuccess', () => {
it('commits RECEIVE_TEMPLATE_TYPES_SUCCESS', (done) => {
testAction(
it('commits RECEIVE_TEMPLATE_TYPES_SUCCESS', () => {
return testAction(
actions.receiveTemplateTypesSuccess,
'test',
state,
[{ type: types.RECEIVE_TEMPLATE_TYPES_SUCCESS, payload: 'test' }],
[],
done,
);
});
});
......@@ -81,23 +78,17 @@ describe('IDE file templates actions', () => {
});
});
it('rejects if selectedTemplateType is empty', (done) => {
it('rejects if selectedTemplateType is empty', async () => {
const dispatch = jest.fn().mockName('dispatch');
actions
.fetchTemplateTypes({ dispatch, state })
.then(done.fail)
.catch(() => {
expect(dispatch).not.toHaveBeenCalled();
done();
});
await expect(actions.fetchTemplateTypes({ dispatch, state })).rejects.toBeUndefined();
expect(dispatch).not.toHaveBeenCalled();
});
it('dispatches actions', (done) => {
it('dispatches actions', () => {
state.selectedTemplateType = { key: 'licenses' };
testAction(
return testAction(
actions.fetchTemplateTypes,
null,
state,
......@@ -111,7 +102,6 @@ describe('IDE file templates actions', () => {
payload: pages[0].concat(pages[1]).concat(pages[2]),
},
],
done,
);
});
});
......@@ -121,16 +111,15 @@ describe('IDE file templates actions', () => {
mock.onGet(/api\/(.*)\/templates\/licenses/).replyOnce(500);
});
it('dispatches actions', (done) => {
it('dispatches actions', () => {
state.selectedTemplateType = { key: 'licenses' };
testAction(
return testAction(
actions.fetchTemplateTypes,
null,
state,
[],
[{ type: 'requestTemplateTypes' }, { type: 'receiveTemplateTypesError' }],
done,
);
});
});
......@@ -184,8 +173,8 @@ describe('IDE file templates actions', () => {
});
describe('receiveTemplateError', () => {
it('dispatches setErrorMessage', (done) => {
testAction(
it('dispatches setErrorMessage', () => {
return testAction(
actions.receiveTemplateError,
'test',
state,
......@@ -201,7 +190,6 @@ describe('IDE file templates actions', () => {
},
},
],
done,
);
});
});
......@@ -217,46 +205,43 @@ describe('IDE file templates actions', () => {
.replyOnce(200, { content: 'testing content' });
});
it('dispatches setFileTemplate if template already has content', (done) => {
it('dispatches setFileTemplate if template already has content', () => {
const template = { content: 'already has content' };
testAction(
return testAction(
actions.fetchTemplate,
template,
state,
[],
[{ type: 'setFileTemplate', payload: template }],
done,
);
});
it('dispatches success', (done) => {
it('dispatches success', () => {
const template = { key: 'mit' };
state.selectedTemplateType = { key: 'licenses' };
testAction(
return testAction(
actions.fetchTemplate,
template,
state,
[],
[{ type: 'setFileTemplate', payload: { content: 'MIT content' } }],
done,
);
});
it('dispatches success and uses name key for API call', (done) => {
it('dispatches success and uses name key for API call', () => {
const template = { name: 'testing' };
state.selectedTemplateType = { key: 'licenses' };
testAction(
return testAction(
actions.fetchTemplate,
template,
state,
[],
[{ type: 'setFileTemplate', payload: { content: 'testing content' } }],
done,
);
});
});
......@@ -266,18 +251,17 @@ describe('IDE file templates actions', () => {
mock.onGet(/api\/(.*)\/templates\/licenses\/mit/).replyOnce(500);
});
it('dispatches error', (done) => {
it('dispatches error', () => {
const template = { name: 'testing' };
state.selectedTemplateType = { key: 'licenses' };
testAction(
return testAction(
actions.fetchTemplate,
template,
state,
[],
[{ type: 'receiveTemplateError', payload: template }],
done,
);
});
});
......
......@@ -28,21 +28,20 @@ describe('IDE merge requests actions', () => {
});
describe('requestMergeRequests', () => {
it('should commit request', (done) => {
testAction(
it('should commit request', () => {
return testAction(
requestMergeRequests,
null,
mockedState,
[{ type: types.REQUEST_MERGE_REQUESTS }],
[],
done,
);
});
});
describe('receiveMergeRequestsError', () => {
it('should commit error', (done) => {
testAction(
it('should commit error', () => {
return testAction(
receiveMergeRequestsError,
{ type: 'created', search: '' },
mockedState,
......@@ -58,20 +57,18 @@ describe('IDE merge requests actions', () => {
},
},
],
done,
);
});
});
describe('receiveMergeRequestsSuccess', () => {
it('should commit received data', (done) => {
testAction(
it('should commit received data', () => {
return testAction(
receiveMergeRequestsSuccess,
mergeRequests,
mockedState,
[{ type: types.RECEIVE_MERGE_REQUESTS_SUCCESS, payload: mergeRequests }],
[],
done,
);
});
});
......@@ -118,8 +115,8 @@ describe('IDE merge requests actions', () => {
});
});
it('dispatches success with received data', (done) => {
testAction(
it('dispatches success with received data', () => {
return testAction(
fetchMergeRequests,
{ type: 'created' },
mockedState,
......@@ -129,7 +126,6 @@ describe('IDE merge requests actions', () => {
{ type: 'resetMergeRequests' },
{ type: 'receiveMergeRequestsSuccess', payload: mergeRequests },
],
done,
);
});
});
......@@ -156,8 +152,8 @@ describe('IDE merge requests actions', () => {
);
});
it('dispatches success with received data', (done) => {
testAction(
it('dispatches success with received data', () => {
return testAction(
fetchMergeRequests,
{ type: null },
{ ...mockedState, ...mockedRootState },
......@@ -167,7 +163,6 @@ describe('IDE merge requests actions', () => {
{ type: 'resetMergeRequests' },
{ type: 'receiveMergeRequestsSuccess', payload: mergeRequests },
],
done,
);
});
});
......@@ -177,8 +172,8 @@ describe('IDE merge requests actions', () => {
mock.onGet(/\/api\/v4\/merge_requests(.*)$/).replyOnce(500);
});
it('dispatches error', (done) => {
testAction(
it('dispatches error', () => {
return testAction(
fetchMergeRequests,
{ type: 'created', search: '' },
mockedState,
......@@ -188,21 +183,19 @@ describe('IDE merge requests actions', () => {
{ type: 'resetMergeRequests' },
{ type: 'receiveMergeRequestsError', payload: { type: 'created', search: '' } },
],
done,
);
});
});
});
describe('resetMergeRequests', () => {
it('commits reset', (done) => {
testAction(
it('commits reset', () => {
return testAction(
resetMergeRequests,
null,
mockedState,
[{ type: types.RESET_MERGE_REQUESTS }],
[],
done,
);
});
});
......
......@@ -7,19 +7,19 @@ describe('IDE pane module actions', () => {
const TEST_VIEW_KEEP_ALIVE = { name: 'test-keep-alive', keepAlive: true };
describe('toggleOpen', () => {
it('dispatches open if closed', (done) => {
testAction(actions.toggleOpen, TEST_VIEW, { isOpen: false }, [], [{ type: 'open' }], done);
it('dispatches open if closed', () => {
return testAction(actions.toggleOpen, TEST_VIEW, { isOpen: false }, [], [{ type: 'open' }]);
});
it('dispatches close if opened', (done) => {
testAction(actions.toggleOpen, TEST_VIEW, { isOpen: true }, [], [{ type: 'close' }], done);
it('dispatches close if opened', () => {
return testAction(actions.toggleOpen, TEST_VIEW, { isOpen: true }, [], [{ type: 'close' }]);
});
});
describe('open', () => {
describe('with a view specified', () => {
it('commits SET_OPEN and SET_CURRENT_VIEW', (done) => {
testAction(
it('commits SET_OPEN and SET_CURRENT_VIEW', () => {
return testAction(
actions.open,
TEST_VIEW,
{},
......@@ -28,12 +28,11 @@ describe('IDE pane module actions', () => {
{ type: types.SET_CURRENT_VIEW, payload: TEST_VIEW.name },
],
[],
done,
);
});
it('commits KEEP_ALIVE_VIEW if keepAlive is true', (done) => {
testAction(
it('commits KEEP_ALIVE_VIEW if keepAlive is true', () => {
return testAction(
actions.open,
TEST_VIEW_KEEP_ALIVE,
{},
......@@ -43,28 +42,26 @@ describe('IDE pane module actions', () => {
{ type: types.KEEP_ALIVE_VIEW, payload: TEST_VIEW_KEEP_ALIVE.name },
],
[],
done,
);
});
});
describe('without a view specified', () => {
it('commits SET_OPEN', (done) => {
testAction(
it('commits SET_OPEN', () => {
return testAction(
actions.open,
undefined,
{},
[{ type: types.SET_OPEN, payload: true }],
[],
done,
);
});
});
});
describe('close', () => {
it('commits SET_OPEN', (done) => {
testAction(actions.close, null, {}, [{ type: types.SET_OPEN, payload: false }], [], done);
it('commits SET_OPEN', () => {
return testAction(actions.close, null, {}, [{ type: types.SET_OPEN, payload: false }], []);
});
});
});
......@@ -25,6 +25,7 @@ import {
import * as types from '~/ide/stores/modules/pipelines/mutation_types';
import state from '~/ide/stores/modules/pipelines/state';
import axios from '~/lib/utils/axios_utils';
import waitForPromises from 'helpers/wait_for_promises';
import { pipelines, jobs } from '../../../mock_data';
describe('IDE pipelines actions', () => {
......@@ -44,32 +45,30 @@ describe('IDE pipelines actions', () => {
});
describe('requestLatestPipeline', () => {
it('commits request', (done) => {
testAction(
it('commits request', () => {
return testAction(
requestLatestPipeline,
null,
mockedState,
[{ type: types.REQUEST_LATEST_PIPELINE }],
[],
done,
);
});
});
describe('receiveLatestPipelineError', () => {
it('commits error', (done) => {
testAction(
it('commits error', () => {
return testAction(
receiveLatestPipelineError,
{ status: 404 },
mockedState,
[{ type: types.RECEIVE_LASTEST_PIPELINE_ERROR }],
[{ type: 'stopPipelinePolling' }],
done,
);
});
it('dispatches setErrorMessage is not 404', (done) => {
testAction(
it('dispatches setErrorMessage is not 404', () => {
return testAction(
receiveLatestPipelineError,
{ status: 500 },
mockedState,
......@@ -86,7 +85,6 @@ describe('IDE pipelines actions', () => {
},
{ type: 'stopPipelinePolling' },
],
done,
);
});
});
......@@ -123,7 +121,7 @@ describe('IDE pipelines actions', () => {
.reply(200, { data: { foo: 'bar' } }, { 'poll-interval': '10000' });
});
it('dispatches request', (done) => {
it('dispatches request', async () => {
jest.spyOn(axios, 'get');
jest.spyOn(Visibility, 'hidden').mockReturnValue(false);
......@@ -133,34 +131,21 @@ describe('IDE pipelines actions', () => {
currentProject: { path_with_namespace: 'abc/def' },
};
fetchLatestPipeline({ dispatch, rootGetters });
await fetchLatestPipeline({ dispatch, rootGetters });
expect(dispatch).toHaveBeenCalledWith('requestLatestPipeline');
jest.advanceTimersByTime(1000);
new Promise((resolve) => requestAnimationFrame(resolve))
.then(() => {
expect(axios.get).toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(
'receiveLatestPipelineSuccess',
expect.anything(),
);
jest.advanceTimersByTime(10000);
})
.then(() => new Promise((resolve) => requestAnimationFrame(resolve)))
.then(() => {
expect(axios.get).toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenCalledWith(
'receiveLatestPipelineSuccess',
expect.anything(),
);
})
.then(done)
.catch(done.fail);
await waitForPromises();
expect(axios.get).toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith('receiveLatestPipelineSuccess', expect.anything());
jest.advanceTimersByTime(10000);
expect(axios.get).toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenCalledWith('receiveLatestPipelineSuccess', expect.anything());
});
});
......@@ -169,27 +154,22 @@ describe('IDE pipelines actions', () => {
mock.onGet('/abc/def/commit/abc123def456ghi789jkl/pipelines').reply(500);
});
it('dispatches error', (done) => {
it('dispatches error', async () => {
const dispatch = jest.fn().mockName('dispatch');
const rootGetters = {
lastCommit: { id: 'abc123def456ghi789jkl' },
currentProject: { path_with_namespace: 'abc/def' },
};
fetchLatestPipeline({ dispatch, rootGetters });
await fetchLatestPipeline({ dispatch, rootGetters });
jest.advanceTimersByTime(1500);
await waitForPromises();
new Promise((resolve) => requestAnimationFrame(resolve))
.then(() => {
expect(dispatch).toHaveBeenCalledWith('receiveLatestPipelineError', expect.anything());
})
.then(done)
.catch(done.fail);
expect(dispatch).toHaveBeenCalledWith('receiveLatestPipelineError', expect.anything());
});
});
it('sets latest pipeline to `null` and stops polling on empty project', (done) => {
it('sets latest pipeline to `null` and stops polling on empty project', () => {
mockedState = {
...mockedState,
rootGetters: {
......@@ -197,26 +177,31 @@ describe('IDE pipelines actions', () => {
},
};
testAction(
return testAction(
fetchLatestPipeline,
{},
mockedState,
[{ type: types.RECEIVE_LASTEST_PIPELINE_SUCCESS, payload: null }],
[{ type: 'stopPipelinePolling' }],
done,
);
});
});
describe('requestJobs', () => {
it('commits request', (done) => {
testAction(requestJobs, 1, mockedState, [{ type: types.REQUEST_JOBS, payload: 1 }], [], done);
it('commits request', () => {
return testAction(
requestJobs,
1,
mockedState,
[{ type: types.REQUEST_JOBS, payload: 1 }],
[],
);
});
});
describe('receiveJobsError', () => {
it('commits error', (done) => {
testAction(
it('commits error', () => {
return testAction(
receiveJobsError,
{ id: 1 },
mockedState,
......@@ -232,20 +217,18 @@ describe('IDE pipelines actions', () => {
},
},
],
done,
);
});
});
describe('receiveJobsSuccess', () => {
it('commits data', (done) => {
testAction(
it('commits data', () => {
return testAction(
receiveJobsSuccess,
{ id: 1, data: jobs },
mockedState,
[{ type: types.RECEIVE_JOBS_SUCCESS, payload: { id: 1, data: jobs } }],
[],
done,
);
});
});
......@@ -258,8 +241,8 @@ describe('IDE pipelines actions', () => {
mock.onGet(stage.dropdownPath).replyOnce(200, jobs);
});
it('dispatches request', (done) => {
testAction(
it('dispatches request', () => {
return testAction(
fetchJobs,
stage,
mockedState,
......@@ -268,7 +251,6 @@ describe('IDE pipelines actions', () => {
{ type: 'requestJobs', payload: stage.id },
{ type: 'receiveJobsSuccess', payload: { id: stage.id, data: jobs } },
],
done,
);
});
});
......@@ -278,8 +260,8 @@ describe('IDE pipelines actions', () => {
mock.onGet(stage.dropdownPath).replyOnce(500);
});
it('dispatches error', (done) => {
testAction(
it('dispatches error', () => {
return testAction(
fetchJobs,
stage,
mockedState,
......@@ -288,69 +270,64 @@ describe('IDE pipelines actions', () => {
{ type: 'requestJobs', payload: stage.id },
{ type: 'receiveJobsError', payload: stage },
],
done,
);
});
});
});
describe('toggleStageCollapsed', () => {
it('commits collapse', (done) => {
testAction(
it('commits collapse', () => {
return testAction(
toggleStageCollapsed,
1,
mockedState,
[{ type: types.TOGGLE_STAGE_COLLAPSE, payload: 1 }],
[],
done,
);
});
});
describe('setDetailJob', () => {
it('commits job', (done) => {
testAction(
it('commits job', () => {
return testAction(
setDetailJob,
'job',
mockedState,
[{ type: types.SET_DETAIL_JOB, payload: 'job' }],
[{ type: 'rightPane/open', payload: rightSidebarViews.jobsDetail }],
done,
);
});
it('dispatches rightPane/open as pipeline when job is null', (done) => {
testAction(
it('dispatches rightPane/open as pipeline when job is null', () => {
return testAction(
setDetailJob,
null,
mockedState,
[{ type: types.SET_DETAIL_JOB, payload: null }],
[{ type: 'rightPane/open', payload: rightSidebarViews.pipelines }],
done,
);
});
it('dispatches rightPane/open as job', (done) => {
testAction(
it('dispatches rightPane/open as job', () => {
return testAction(
setDetailJob,
'job',
mockedState,
[{ type: types.SET_DETAIL_JOB, payload: 'job' }],
[{ type: 'rightPane/open', payload: rightSidebarViews.jobsDetail }],
done,
);
});
});
describe('requestJobLogs', () => {
it('commits request', (done) => {
testAction(requestJobLogs, null, mockedState, [{ type: types.REQUEST_JOB_LOGS }], [], done);
it('commits request', () => {
return testAction(requestJobLogs, null, mockedState, [{ type: types.REQUEST_JOB_LOGS }], []);
});
});
describe('receiveJobLogsError', () => {
it('commits error', (done) => {
testAction(
it('commits error', () => {
return testAction(
receiveJobLogsError,
null,
mockedState,
......@@ -366,20 +343,18 @@ describe('IDE pipelines actions', () => {
},
},
],
done,
);
});
});
describe('receiveJobLogsSuccess', () => {
it('commits data', (done) => {
testAction(
it('commits data', () => {
return testAction(
receiveJobLogsSuccess,
'data',
mockedState,
[{ type: types.RECEIVE_JOB_LOGS_SUCCESS, payload: 'data' }],
[],
done,
);
});
});
......@@ -395,8 +370,8 @@ describe('IDE pipelines actions', () => {
mock.onGet(`${TEST_HOST}/project/builds/trace`).replyOnce(200, { html: 'html' });
});
it('dispatches request', (done) => {
testAction(
it('dispatches request', () => {
return testAction(
fetchJobLogs,
null,
mockedState,
......@@ -405,7 +380,6 @@ describe('IDE pipelines actions', () => {
{ type: 'requestJobLogs' },
{ type: 'receiveJobLogsSuccess', payload: { html: 'html' } },
],
done,
);
});
......@@ -426,22 +400,21 @@ describe('IDE pipelines actions', () => {
mock.onGet(`${TEST_HOST}/project/builds/trace`).replyOnce(500);
});
it('dispatches error', (done) => {
testAction(
it('dispatches error', () => {
return testAction(
fetchJobLogs,
null,
mockedState,
[],
[{ type: 'requestJobLogs' }, { type: 'receiveJobLogsError' }],
done,
);
});
});
});
describe('resetLatestPipeline', () => {
it('commits reset mutations', (done) => {
testAction(
it('commits reset mutations', () => {
return testAction(
resetLatestPipeline,
null,
mockedState,
......@@ -450,7 +423,6 @@ describe('IDE pipelines actions', () => {
{ type: types.SET_DETAIL_JOB, payload: null },
],
[],
done,
);
});
});
......
......@@ -22,43 +22,37 @@ describe('ide/stores/modules/terminal_sync/actions', () => {
});
describe('upload', () => {
it('uploads to mirror and sets success', (done) => {
it('uploads to mirror and sets success', async () => {
mirror.upload.mockReturnValue(Promise.resolve());
testAction(
await testAction(
actions.upload,
null,
rootState,
[{ type: types.START_LOADING }, { type: types.SET_SUCCESS }],
[],
() => {
expect(mirror.upload).toHaveBeenCalledWith(rootState);
done();
},
);
expect(mirror.upload).toHaveBeenCalledWith(rootState);
});
it('sets error when failed', (done) => {
it('sets error when failed', () => {
const err = { message: 'it failed!' };
mirror.upload.mockReturnValue(Promise.reject(err));
testAction(
return testAction(
actions.upload,
null,
rootState,
[{ type: types.START_LOADING }, { type: types.SET_ERROR, payload: err }],
[],
done,
);
});
});
describe('stop', () => {
it('disconnects from mirror', (done) => {
testAction(actions.stop, null, rootState, [{ type: types.STOP }], [], () => {
expect(mirror.disconnect).toHaveBeenCalled();
done();
});
it('disconnects from mirror', async () => {
await testAction(actions.stop, null, rootState, [{ type: types.STOP }], []);
expect(mirror.disconnect).toHaveBeenCalled();
});
});
......@@ -83,20 +77,17 @@ describe('ide/stores/modules/terminal_sync/actions', () => {
};
});
it('connects to mirror and sets success', (done) => {
it('connects to mirror and sets success', async () => {
mirror.connect.mockReturnValue(Promise.resolve());
testAction(
await testAction(
actions.start,
null,
rootState,
[{ type: types.START_LOADING }, { type: types.SET_SUCCESS }],
[],
() => {
expect(mirror.connect).toHaveBeenCalledWith(TEST_SESSION.proxyWebsocketPath);
done();
},
);
expect(mirror.connect).toHaveBeenCalledWith(TEST_SESSION.proxyWebsocketPath);
});
it('sets error if connection fails', () => {
......
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