Skip to content

Commit

Permalink
test: Cleanup test setup
Browse files Browse the repository at this point in the history
Setup some global location within the setup, also use vmForks so CSS files are correctly mocked
during tests. This allows to not inline nextcloud files so we can properly mock it if needed (e.g. for public share tests).

Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
  • Loading branch information
susnux committed Oct 16, 2024
1 parent d6c3e3c commit 7e22795
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 52 deletions.
9 changes: 9 additions & 0 deletions __mocks__/@nextcloud/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,12 @@ export const getCurrentUser = function() {
isAdmin: false,
}
}

/** Mock the request token */
export function getRequestToken() {
return 'request-token'
}

/** Mock that receives a parameter (callback) */
export function onRequestTokenUpdate() {
}
3 changes: 2 additions & 1 deletion __mocks__/@nextcloud/router.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
/*!
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

export const generateRemoteUrl = (path) => {
return `https://cloud.domain.com/remote.php/${path}`
}
25 changes: 17 additions & 8 deletions __tests__/uploader.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,25 @@
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { beforeEach, describe, expect, it, test, vi } from 'vitest'
import { beforeAll, beforeEach, describe, expect, it, test, vi } from 'vitest'
import { Uploader } from '../lib/uploader'
import * as nextcloudAuth from '@nextcloud/auth'
import * as nextcloudFiles from '@nextcloud/files'

// This mocks auth to always return the `test` user by default
vi.mock('@nextcloud/auth')
vi.mock('@nextcloud/files', async (getModule) => {
const original: typeof nextcloudFiles = await getModule()
return { ...original }
})

beforeAll(() => {
vi.spyOn(nextcloudFiles, 'davRemoteURL', 'get').mockReturnValue('http://cloud.example.com/remote.php/dav')
vi.spyOn(nextcloudFiles, 'davRootPath', 'get').mockReturnValue('/files/test')
})

describe('Uploader', () => {
beforeEach(() => {
vi.restoreAllMocks()
// Reset mocks of DOM
document.body.innerHTML = ''
})
Expand All @@ -24,11 +32,12 @@ describe('Uploader', () => {
})

it('sets default target folder for public share', async () => {
// no logged in user
vi.spyOn(nextcloudAuth, 'getCurrentUser').mockImplementationOnce(() => null)
// public share values
vi.spyOn(nextcloudFiles, 'davRemoteURL', 'get').mockReturnValue('http://example.com/public.php/dav')
vi.spyOn(nextcloudFiles, 'davRootPath', 'get').mockReturnValue('/files/share-token')
vi.spyOn(nextcloudFiles, 'davRemoteURL', 'get')
.mockReturnValueOnce('http://cloud.example.com/public.php/dav')
vi.spyOn(nextcloudFiles, 'davRootPath', 'get')
.mockReturnValueOnce('/files/share-token')
.mockReturnValueOnce('/files/share-token')

const uploader = new Uploader(true)
expect(uploader.destination.source).match(/\/public\.php\/dav\/files\/share-token\/?$/)
Expand Down Expand Up @@ -73,7 +82,7 @@ describe('Uploader', () => {
// This is valid as per RFC7230
const uploader = new Uploader()
uploader.setCustomHeader('Host', '')
expect(uploader.customHeaders).toEqual({ 'Host': '' })
expect(uploader.customHeaders).toEqual({ Host: '' })
})
})

Expand All @@ -96,7 +105,7 @@ describe('Uploader', () => {
const uploader = new Uploader()
expect(uploader.destination.path).toBe('/')

expect(() => { uploader.destination = undefined as any }).toThrowError(/invalid destination/i)
expect(() => { uploader.destination = undefined as never }).toThrowError(/invalid destination/i)
})

test('cannot set file as destination', () => {
Expand Down
53 changes: 16 additions & 37 deletions __tests__/utils/upload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,17 @@
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { beforeAll, afterAll, describe, expect, test, vi } from 'vitest'
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Mock } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
import axios from '@nextcloud/axios'

import { getChunk, initChunkWorkspace, uploadData } from '../../lib/utils/upload.js'

const axiosMock: vi.Mock<typeof axios> | typeof axios = axios
const axiosMock: Mock<typeof axios> | typeof axios = axios

beforeAll(() => {
vi.mock('axios', vi.fn())
})

afterAll(() => {
vi.unmock('axios')
})
vi.mock('@nextcloud/auth')
vi.mock('axios', vi.fn())

describe('Get chunk from file', () => {
test('Chunking a valid file', async () => {
Expand Down Expand Up @@ -65,19 +62,10 @@ describe('Initialize chunks upload temporary workspace', () => {
test('Init random workspace', async () => {
axiosMock.request = vi.fn((config: any) => Promise.resolve(config?.onUploadProgress?.()))

// mock the current location for our assert on the URL
Object.defineProperty(window, 'location', {
value: new URL('https://cloud.domain.com/index.php/apps/test'),
configurable: true,
})

// mock the current user
document.head.setAttribute('data-user', 'test')

const url = await initChunkWorkspace()

expect(url).toMatch('https://cloud.domain.com/remote.php/dav/uploads/test/web-file-upload-')
expect(url.length).toEqual('https://cloud.domain.com/remote.php/dav/uploads/test/web-file-upload-123456789abcdefg'.length)
expect(url).toMatch('https://cloud.example.com/remote.php/dav/uploads/test/web-file-upload-')
expect(url.length).toEqual('https://cloud.example.com/remote.php/dav/uploads/test/web-file-upload-123456789abcdefg'.length)

expect(axiosMock.request).toHaveBeenCalledTimes(1)
expect(axiosMock.request).toHaveBeenCalledWith({
Expand All @@ -93,26 +81,17 @@ describe('Initialize chunks upload temporary workspace', () => {
test('Init random workspace for file destination', async () => {
axiosMock.request = vi.fn((config: any) => Promise.resolve(config?.onUploadProgress?.()))

// mock the current location for our assert on the URL
Object.defineProperty(window, 'location', {
value: new URL('https://cloud.domain.com/index.php/apps/test'),
configurable: true,
})

// mock the current user
document.head.setAttribute('data-user', 'test')

const url = await initChunkWorkspace('https://cloud.domain.com/remote.php/dav/files/test/image.jpg')
const url = await initChunkWorkspace('https://cloud.example.com/remote.php/dav/files/test/image.jpg')

expect(url).toMatch('https://cloud.domain.com/remote.php/dav/uploads/test/web-file-upload-')
expect(url.length).toEqual('https://cloud.domain.com/remote.php/dav/uploads/test/web-file-upload-123456789abcdefg'.length)
expect(url).toMatch('https://cloud.example.com/remote.php/dav/uploads/test/web-file-upload-')
expect(url.length).toEqual('https://cloud.example.com/remote.php/dav/uploads/test/web-file-upload-123456789abcdefg'.length)

expect(axiosMock.request).toHaveBeenCalledTimes(1)
expect(axiosMock.request).toHaveBeenCalledWith({
method: 'MKCOL',
url,
headers: {
Destination: 'https://cloud.domain.com/remote.php/dav/files/test/image.jpg',
Destination: 'https://cloud.example.com/remote.php/dav/files/test/image.jpg',
},
'axios-retry': {
retries: 5,
Expand All @@ -126,7 +105,7 @@ describe('Upload data', () => {
test('Upload data stream', async () => {
axiosMock.request = vi.fn((config: any) => Promise.resolve(config?.onUploadProgress()))

const url = 'https://cloud.domain.com/remote.php/dav/files/test/image.jpg'
const url = 'https://cloud.example.com/remote.php/dav/files/test/image.jpg'
const blob = new Blob([new ArrayBuffer(50 * 1024 * 1024)])
const signal = new AbortController().signal
const onUploadProgress = vi.fn()
Expand All @@ -152,7 +131,7 @@ describe('Upload data', () => {
test('Upload async data stream', async () => {
axiosMock.request = vi.fn((config: any) => Promise.resolve(config?.onUploadProgress()))

const url = 'https://cloud.domain.com/remote.php/dav/files/test/image.jpg'
const url = 'https://cloud.example.com/remote.php/dav/files/test/image.jpg'
const blob = new Blob([new ArrayBuffer(50 * 1024 * 1024)])
const data = vi.fn(async () => blob)
const signal = new AbortController().signal
Expand Down Expand Up @@ -182,7 +161,7 @@ describe('Upload data', () => {
test('Upload data stream with destination', async () => {
axiosMock.request = vi.fn((config: any) => Promise.resolve(config?.onUploadProgress()))

const url = 'https://cloud.domain.com/remote.php/dav/files/test/image.jpg'
const url = 'https://cloud.example.com/remote.php/dav/files/test/image.jpg'
const blob = new Blob([new ArrayBuffer(50 * 1024 * 1024)])
const signal = new AbortController().signal
const onUploadProgress = vi.fn()
Expand Down Expand Up @@ -210,7 +189,7 @@ describe('Upload data', () => {
test('Upload cancellation', async () => {
axiosMock.request = vi.fn((config: any) => Promise.resolve(config?.onUploadProgress()))

const url = 'https://cloud.domain.com/remote.php/dav/files/test/image.jpg'
const url = 'https://cloud.example.com/remote.php/dav/files/test/image.jpg'
const blob = new Blob([new ArrayBuffer(50 * 1024 * 1024)])
const data = vi.fn(async () => blob)
const controller = new AbortController()
Expand Down
13 changes: 7 additions & 6 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import type { UserConfig } from 'vitest'
import type { UserConfig } from 'vitest/node'
import config from './vite.config.ts'

export default async (env) => {
Expand All @@ -12,18 +12,19 @@ export default async (env) => {

cfg.test = {
environment: 'jsdom',
environmentOptions: {
jsdom: {
url: 'https://cloud.example.com/index.php/apps/test',
},
},
setupFiles: '__tests__/setup.ts',
coverage: {
include: ['lib/**'],
// This makes no sense to test
exclude: ['lib/utils/l10n.ts'],
reporter: ['lcov', 'text'],
},
server: {
deps: {
inline: ['@nextcloud/files'],
},
},
pool: 'vmForks',
} as UserConfig
return cfg
}

0 comments on commit 7e22795

Please sign in to comment.