diff --git a/app/assets/javascripts/diffs/store/actions.js b/app/assets/javascripts/diffs/store/actions.js index d40e22cd0a10d236b2081d4b576ca688ff08dfc3..2d94baed1a08dde82b93338db0c5d56cd3044103 100644 --- a/app/assets/javascripts/diffs/store/actions.js +++ b/app/assets/javascripts/diffs/store/actions.js @@ -557,7 +557,7 @@ export const setShowWhitespace = async ( { state, commit }, { url, showWhitespace, updateDatabase = true }, ) => { - if (updateDatabase) { + if (updateDatabase && Boolean(window.gon?.current_user_id)) { await axios.put(url || state.endpointUpdateUser, { show_whitespace_in_diffs: showWhitespace }); } diff --git a/spec/frontend/diffs/store/actions_spec.js b/spec/frontend/diffs/store/actions_spec.js index f25099cdecce013e90065944abf53decad817e11..c2e5d07bcfd3c7915a79ce338009324ceb3317ea 100644 --- a/spec/frontend/diffs/store/actions_spec.js +++ b/spec/frontend/diffs/store/actions_spec.js @@ -1019,10 +1019,12 @@ describe('DiffsStoreActions', () => { const endpointUpdateUser = 'user/prefs'; let putSpy; let mock; + let gon; beforeEach(() => { mock = new MockAdapter(axios); putSpy = jest.spyOn(axios, 'put'); + gon = window.gon; mock.onPut(endpointUpdateUser).reply(200, {}); jest.spyOn(eventHub, '$emit').mockImplementation(); @@ -1030,6 +1032,7 @@ describe('DiffsStoreActions', () => { afterEach(() => { mock.restore(); + window.gon = gon; }); it('commits SET_SHOW_WHITESPACE', (done) => { @@ -1043,7 +1046,9 @@ describe('DiffsStoreActions', () => { ); }); - it('saves to the database', async () => { + it('saves to the database when the user is logged in', async () => { + window.gon = { current_user_id: 12345 }; + await setShowWhitespace( { state: { endpointUpdateUser }, commit() {} }, { showWhitespace: true, updateDatabase: true }, @@ -1052,6 +1057,17 @@ describe('DiffsStoreActions', () => { expect(putSpy).toHaveBeenCalledWith(endpointUpdateUser, { show_whitespace_in_diffs: true }); }); + it('does not try to save to the API if the user is not logged in', async () => { + window.gon = {}; + + await setShowWhitespace( + { state: { endpointUpdateUser }, commit() {} }, + { showWhitespace: true, updateDatabase: true }, + ); + + expect(putSpy).not.toHaveBeenCalled(); + }); + it('emits eventHub event', async () => { await setShowWhitespace( { state: {}, commit() {} },