diff --git a/lib/requesttoken.ts b/lib/requesttoken.ts index 4431d62..6e607e3 100644 --- a/lib/requesttoken.ts +++ b/lib/requesttoken.ts @@ -19,8 +19,7 @@ const observers: CsrfTokenObserver[] = [] export function getRequestToken(): string | null { if (token === undefined) { // Only on first load, try to get token from document - const tokenElement = document?.getElementsByTagName('head')[0] - token = tokenElement ? tokenElement.getAttribute('data-requesttoken') : null + token = document.head.dataset.requesttoken ?? null } return token } @@ -42,7 +41,7 @@ subscribe('csrf-token-update', (e: unknown) => { try { observer(token!) } catch (e) { - console.error('error updating CSRF token observer', e) + console.error('Error updating CSRF token observer', e) } }) }) diff --git a/test/request-token.test.ts b/test/request-token.test.ts index 0121b73..90bc2ce 100644 --- a/test/request-token.test.ts +++ b/test/request-token.test.ts @@ -5,20 +5,27 @@ import { emit } from '@nextcloud/event-bus' import { beforeEach, describe, expect, test, vi } from 'vitest' -import { getRequestToken, onRequestTokenUpdate } from '../lib/index' - describe('request token', () => { beforeEach(() => { - emit('csrf-token-update', { - token: undefined, - }) + vi.resetModules() + vi.resetAllMocks() + delete document.head.dataset.requesttoken }) - test('updates token via event', () => { + test('return null if no token found', async () => { + const { getRequestToken } = await import('../lib') expect(getRequestToken()).toBe(null) }) - test('find correct value', () => { + test('read initial token', async () => { + document.head.dataset.requesttoken = 'random-token' + const { getRequestToken } = await import('../lib') + expect(getRequestToken()).toBe('random-token') + }) + + test('can update token by event', async () => { + const { getRequestToken } = await import('../lib') + emit('csrf-token-update', { token: 'token123', }) @@ -26,7 +33,8 @@ describe('request token', () => { expect(getRequestToken()).toBe('token123') }) - test('request token observer is called', () => { + test('request token observer is called', async () => { + const { onRequestTokenUpdate } = await import('../lib') const observer = vi.fn(() => { }) onRequestTokenUpdate(observer) @@ -36,4 +44,20 @@ describe('request token', () => { expect(observer.mock.calls.length).toBe(1) }) + + test('handle exception in observer', async () => { + const spy = vi.spyOn(window.console, 'error') + const { onRequestTokenUpdate } = await import('../lib') + const observer = vi.fn(() => { throw new Error('!Error!') }) + // silence the console + spy.mockImplementationOnce(() => {}) + + onRequestTokenUpdate(observer) + emit('csrf-token-update', { + token: 'token123', + }) + + expect(observer.mock.calls.length).toBe(1) + expect(spy).toHaveBeenCalledOnce() + }) })