Skip to content
Snippets Groups Projects
Commit fdb4b2c1 authored by richard.petersen's avatar richard.petersen :sailboat:
Browse files

Replace jest with mocha

parent b231d358
No related branches found
No related tags found
No related merge requests found
module.exports = {
spec: ['spec/**/*_test.js'],
}
\ No newline at end of file
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/51/r4dxfwvd2cn70x7vhpyh88480000gn/T/jest_dx",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
collectCoverageFrom: ['index.js'],
// The directory where Jest should output its coverage files
coverageDirectory: 'output/coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
coverageReporters: [
'text',
'cobertura',
'text-summary'
],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
maxWorkers: 1,
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: ['./spec/setup.js'],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: ['jest-extended'],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
testMatch: [
'**/spec/**/*_(spec|test).js'
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
testResultsProcessor: 'jest-junit'
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
}
source diff could not be displayed: it is too large. Options to address this: view the blob.
......@@ -9,7 +9,7 @@
"start": "node src/index.js",
"dev": "nodemon index.js",
"prepare": "husky install",
"test": "LOG_LEVEL=error NODE_OPTIONS=--experimental-vm-modules jest --no-cache",
"test": "LOG_LEVEL=error mocha --parallel",
"release-chart": "cd helm/core-ui-middleware/ && npx --package=@open-xchange/release-it -- release-it",
"release-app": "npx --package=@open-xchange/release-it -- release-it",
"release": "yarn release-chart && yarn release-app"
......@@ -21,7 +21,6 @@
"@open-xchange/logging": "^0.0.9",
"@open-xchange/metrics": "^0.0.1",
"dotenv-defaults": "^5.0.0",
"eslint-config-standard": "^16.0.2",
"express": "^4.17.1",
"helmet": "^5.0.1",
"js-yaml": "^4.0.0",
......@@ -29,22 +28,21 @@
"swagger-ui-express": "^4.1.6"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"chai": "^4.3.6",
"eslint": "^8.6.0",
"eslint-config-standard": "^16.0.2",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jest": "^26.0.0",
"eslint-plugin-mocha": "^10.0.3",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.0.0",
"husky": ">=6",
"jest": "^27.1.0",
"jest-extended": "^1.2.0",
"jest-junit": "^13.0.0",
"lint-staged": ">=10",
"mock-fs": "^5.0.0",
"mocha": "^9.2.1",
"nodemon": "^2.0.7",
"superagent": "^7.1.1",
"supertest": "^6.1.6"
"supertest": "^6.1.6",
"testdouble": "^3.16.4"
},
"lint-staged": {
"*.js": "eslint --cache --fix"
......
{
"env": {
"jest/globals": true
},
"plugins": ["jest"]
"extends": [
"plugin:mocha/recommended"
],
"plugins": ["mocha"]
}
import { describe, it, expect } from '@jest/globals'
import { viteManifestToDeps } from '../src/manifests.js'
import { expect } from 'chai'
describe('Vite manifest parsing', () => {
it('works for simple modules', () => {
describe('Vite manifest parsing', function () {
it('works for simple modules', function () {
const deps = viteManifestToDeps({
'../io.ox/guidedtours/i18n.de_DE.js': {
file: 'io.ox/guidedtours/i18n.de_DE.js',
......@@ -98,13 +97,13 @@ describe('Vite manifest parsing', () => {
file: 'io.ox/guidedtours/preload-helper-a7bbbf37.js'
}
})
expect(typeof deps).toBe('object')
expect(Object.keys(deps).length).toBe(8)
expect(deps['io.ox/guidedtours/main.07676e21.js']).toEqual(['io.ox/guidedtours/preload-helper-a7bbbf37.js', 'io.ox/guidedtours/i18n.3de05d46.js'])
expect(deps['io.ox/guidedtours/multifactor.22d3e17d.js']).toEqual(['io.ox/guidedtours/preload-helper-a7bbbf37.js', 'io.ox/guidedtours/i18n.3de05d46.js', 'io.ox/guidedtours/main.07676e21.js', 'io.ox/guidedtours/assets/multifactor.91962241.css'])
expect(typeof deps).to.equal('object')
expect(Object.keys(deps).length).to.equal(8)
expect(deps['io.ox/guidedtours/main.07676e21.js']).to.deep.equal(['io.ox/guidedtours/preload-helper-a7bbbf37.js', 'io.ox/guidedtours/i18n.3de05d46.js'])
expect(deps['io.ox/guidedtours/multifactor.22d3e17d.js']).to.deep.equal(['io.ox/guidedtours/preload-helper-a7bbbf37.js', 'io.ox/guidedtours/i18n.3de05d46.js', 'io.ox/guidedtours/main.07676e21.js', 'io.ox/guidedtours/assets/multifactor.91962241.css'])
})
it('exports assets as entrypoints without dependencies', async () => {
it('exports assets as entrypoints without dependencies', async function () {
const deps = viteManifestToDeps({
'themes/icons/alarm.svg': {
file: 'assets/alarm.6d2fbb40.js',
......@@ -116,12 +115,12 @@ describe('Vite manifest parsing', () => {
meta: {}
}
})
expect(Object.keys(deps).length).toBe(2)
expect(deps['assets/alarm.6d2fbb40.js']).toEqual(['assets/alarm.310541a0.svg'])
expect(deps['assets/alarm.310541a0.svg']).toEqual([])
expect(Object.keys(deps).length).to.equal(2)
expect(deps['assets/alarm.6d2fbb40.js']).to.deep.equal(['assets/alarm.310541a0.svg'])
expect(deps['assets/alarm.310541a0.svg']).to.deep.equal([])
})
it('exports css as entrypoints without dependencies', async () => {
it('exports css as entrypoints without dependencies', async function () {
const deps = viteManifestToDeps({
'main.js': {
file: 'main.js',
......@@ -131,11 +130,11 @@ describe('Vite manifest parsing', () => {
meta: {}
}
})
expect(deps['main.js']).toEqual(['assets/main.3b761440.css'])
expect(deps['assets/main.3b761440.css']).toEqual([])
expect(deps['main.js']).to.deep.equal(['assets/main.3b761440.css'])
expect(deps['assets/main.3b761440.css']).to.deep.equal([])
})
it('separately exports HTML entrypoints', async () => {
it('separately exports HTML entrypoints', async function () {
const deps = viteManifestToDeps({
'index.html': {
file: 'index.html.js',
......@@ -168,7 +167,7 @@ describe('Vite manifest parsing', () => {
}
})
expect(Object.keys(deps).length).toBe(7)
expect(deps['index.html']).toEqual(['index.html.js'])
expect(Object.keys(deps).length).to.equal(7)
expect(deps['index.html']).to.deep.equal(['index.html.js'])
})
})
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from '@jest/globals'
import mockfs from 'mock-fs'
import request from 'supertest'
import { createApp } from '../src/createApp'
import { createMockServer, generateSimpleViteManifest, getRandomPort } from './util.js'
import { createApp } from '../src/createApp.js'
import { createMockServer, generateSimpleViteManifest, getRandomPort, mockConfig } from './util.js'
import { expect } from 'chai'
describe('JS files with dependencies contain events', () => {
const port = getRandomPort()
describe('JS files with dependencies contain events', function () {
let app
let mockserver
const port = getRandomPort()
let restoreConfig
beforeAll(() => {
mockfs({
'./config': {
'config.yaml': `baseUrls:
- http://localhost:${port}`
}
})
before(function () {
;({ restore: restoreConfig } = mockConfig({ urls: [`http://localhost:${port}/`] }))
app = createApp()
})
afterAll(() => {
mockfs.restore()
after(function () {
restoreConfig()
})
beforeEach(async () => {
beforeEach(async function () {
mockserver = await createMockServer({ port })
mockserver.respondWith({
'/manifest.json': generateSimpleViteManifest({
......@@ -44,15 +40,15 @@ describe('JS files with dependencies contain events', () => {
await request(app).get('/ready')
})
afterEach(() => {
afterEach(function () {
mockserver.close()
process.env.CACHE_TTL = 30000
})
it('javascript file contains dispatcher for dependencies', async () => {
it('javascript file contains dispatcher for dependencies', async function () {
const response = await request(app).get('/index.html.js')
expect(response.statusCode).toBe(200)
expect(response.headers.dependencies).toEqual('main.css')
expect(response.text).toEqual('console.log("this is index.html.js")\n/*injected by ui-middleware*/document.dispatchEvent(new CustomEvent("load-css",{detail:{css:["main.css"]}}))')
expect(response.statusCode).to.equal(200)
expect(response.headers.dependencies).to.equal('main.css')
expect(response.text).to.equal('console.log("this is index.html.js")\n/*injected by ui-middleware*/document.dispatchEvent(new CustomEvent("load-css",{detail:{css:["main.css"]}}))')
})
})
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from '@jest/globals'
import mockfs from 'mock-fs'
import request from 'supertest'
import { createApp } from '../src/createApp'
import { createMockServer, generateSimpleViteManifest, getRandomPort } from './util.js'
import { createApp } from '../src/createApp.js'
import { createMockServer, generateSimpleViteManifest, getRandomPort, mockConfig } from './util.js'
import fs from 'fs'
import { expect } from 'chai'
const image = fs.readFileSync('./spec/media/image.png')
const imageStat = fs.statSync('./spec/media/image.png')
const port = getRandomPort()
describe('File caching service', () => {
describe('File caching service', function () {
let app
let mockserver
const port = getRandomPort()
let restoreConfig
beforeAll(() => {
mockfs({
'./config': {
'config.yaml': `baseUrls:
- http://localhost:${port}/`
}
})
before(function () {
;({ restore: restoreConfig } = mockConfig({ urls: [`http://localhost:${port}/`] }))
app = createApp()
})
afterAll(() => {
mockfs.restore()
after(function () {
restoreConfig()
})
beforeEach(async () => {
beforeEach(async function () {
mockserver = await createMockServer({ port })
mockserver.respondWith({
'/manifest.json': generateSimpleViteManifest({
......@@ -60,58 +55,58 @@ describe('File caching service', () => {
await request(app).get('/ready')
})
afterEach(() => {
afterEach(function () {
mockserver.close()
process.env.CACHE_TTL = 30000
})
it('serves files defined in manifest.json file', async () => {
it('serves files defined in manifest.json file', async function () {
const response = await request(app).get('/example.js')
expect(response.statusCode).toBe(200)
expect(response.headers['content-type']).toBe('application/javascript; charset=utf-8')
expect(response.text).toBe('this is example')
// expect(response.headers['content-security-policy']).toContain('sha256-NzZhMTE2Njc2YTgyNTZmZTdlZGVjZDU3YTNmYzRjNmM1OWZkMTI2NjRkYzZmMWM3YTkwMGU3ZTdhNDlhZmVlMwo=')
expect(response.statusCode).to.equal(200)
expect(response.headers['content-type']).to.equal('application/javascript; charset=utf-8')
expect(response.text).to.equal('this is example')
// expect(response.headers['content-security-policy']).to.contain('sha256-NzZhMTE2Njc2YTgyNTZmZTdlZGVjZDU3YTNmYzRjNmM1OWZkMTI2NjRkYzZmMWM3YTkwMGU3ZTdhNDlhZmVlMwo=')
const response2 = await request(app).get('/test.txt')
expect(response2.statusCode).toBe(200)
expect(response2.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(response2.text).toBe('this is test')
expect(response2.statusCode).to.equal(200)
expect(response2.headers['content-type']).to.equal('text/plain; charset=utf-8')
expect(response2.text).to.equal('this is test')
})
it('serves css files', async () => {
it('serves css files', async function () {
const response = await request(app).get('/main.css')
expect(response.statusCode).toBe(200)
expect(response.headers['content-type']).toBe('text/css; charset=utf-8')
// expect(response.headers['content-security-policy']).toContain('sha256-YjRiYWRlYTVhYmM5ZTZkNjE2ZGM4YjcwZWRlNzUxMmU0YjgxY2UxMWExOTI2ZjM1NzM1M2Y2MWJjNmUwMmZjMwo=')
expect(response.statusCode).to.equal(200)
expect(response.headers['content-type']).to.equal('text/css; charset=utf-8')
// expect(response.headers['content-security-policy']).to.contain('sha256-YjRiYWRlYTVhYmM5ZTZkNjE2ZGM4YjcwZWRlNzUxMmU0YjgxY2UxMWExOTI2ZjM1NzM1M2Y2MWJjNmUwMmZjMwo=')
})
it('serves / as index.html', async () => {
it('serves / as index.html', async function () {
const response = await request(app).get('/')
expect(response.statusCode).toBe(200)
expect(response.headers['content-type']).toBe('text/html; charset=utf-8')
expect(response.text).toBe('<html><head></head><body>it\'s me</body></html>')
expect(response.statusCode).to.equal(200)
expect(response.headers['content-type']).to.equal('text/html; charset=utf-8')
expect(response.text).to.equal('<html><head></head><body>it\'s me</body></html>')
})
it('adds / to dependencies', async () => {
it('adds / to dependencies', async function () {
const response = await request(app).get('/dependencies')
expect(response.statusCode).toBe(200)
expect(response.statusCode).to.equal(200)
const deps = JSON.parse(response.text)
expect(deps['/']).toEqual([])
expect(deps['/']).to.deep.equal([])
})
it('directly fetches files not referenced in manifest.json files from the upstream servers', async () => {
it('directly fetches files not referenced in manifest.json files from the upstream servers', async function () {
const response = await request(app).get('/favicon.ico')
expect(response.statusCode).toBe(200)
expect(response.body).toBe('not really a favicon, though')
expect(response.statusCode).to.equal(200)
expect(response.body).to.equal('not really a favicon, though')
})
it('returns 404 if file can not be resolved', async () => {
it('returns 404 if file can not be resolved', async function () {
const response = await request(app).get('/unknown-file.txt')
expect(response.statusCode).toBe(404)
expect(response.statusCode).to.equal(404)
})
it('serves binary files', async () => {
it('serves binary files', async function () {
const response = await request(app).get('/image.png')
expect(response.statusCode).toBe(200)
expect(response.statusCode).to.equal(200)
expect(response.body.length === imageStat.size)
})
})
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from '@jest/globals'
import mockfs from 'mock-fs'
import request from 'supertest'
import { createApp } from '../src/createApp'
import { createMockServer, generateSimpleViteManifest, getRandomPort } from './util.js'
import { createApp } from '../src/createApp.js'
import { createMockServer, generateSimpleViteManifest, getRandomPort, mockConfig } from './util.js'
import { expect } from 'chai'
describe('Responses contain custom headers', () => {
const port = getRandomPort()
describe('Responses contain custom headers', function () {
let app
let mockserver
const port = getRandomPort()
beforeAll(() => {
mockfs({
'./config': {
'config.yaml': `baseUrls:
- http://localhost:${port}`
}
})
let restoreConfig
before(function () {
;({ restore: restoreConfig } = mockConfig({ urls: [`http://localhost:${port}/`] }))
app = createApp()
})
afterAll(() => {
mockfs.restore()
after(function () {
restoreConfig()
})
beforeEach(async () => {
beforeEach(async function () {
mockserver = await createMockServer({ port })
mockserver.respondWith({
'/manifest.json': generateSimpleViteManifest({
......@@ -44,20 +40,20 @@ describe('Responses contain custom headers', () => {
await request(app).get('/ready')
})
afterEach(() => {
afterEach(function () {
mockserver.close()
process.env.CACHE_TTL = 30000
})
it('index.html has version', async () => {
it('index.html has version', async function () {
const response = await request(app).get('/index.html')
expect(response.statusCode).toBe(200)
expect(response.headers.version).toMatch(/\d*\.\d*/)
expect(response.statusCode).to.equal(200)
expect(response.headers.version).to.match(/\d*\.\d*/)
})
it('javascript file contains dependencies', async () => {
it('javascript file contains dependencies', async function () {
const response = await request(app).get('/index.html.js')
expect(response.statusCode).toBe(200)
expect(response.headers.dependencies).toEqual('main.css')
expect(response.statusCode).to.equal(200)
expect(response.headers.dependencies).to.equal('main.css')
})
})
import { describe, it, expect } from '@jest/globals'
import { viteToOxManifest } from '../src/manifests.js'
import { expect } from 'chai'
describe('Vite manifest parsing', () => {
it('should', () => {
describe('Vite manifest parsing', function () {
it('should', function () {
const manifests = viteToOxManifest({
'../io.ox/guidedtours/i18n.de_DE.js': {
file: 'io.ox/guidedtours/i18n.de_DE.js',
......@@ -95,19 +94,19 @@ describe('Vite manifest parsing', () => {
file: 'io.ox/guidedtours/preload-helper-a7bbbf37.js'
}
})
expect(Array.isArray(manifests)).toBe(true)
expect(manifests.length).toBe(3)
expect(manifests.map(manifest => manifest.path)).toEqual([
expect(Array.isArray(manifests)).to.equal(true)
expect(manifests.length).to.equal(3)
expect(manifests.map(manifest => manifest.path)).to.deep.equal([
'io.ox/guidedtours/i18n.3de05d46',
'io.ox/guidedtours/main.07676e21',
'io.ox/guidedtours/main.07676e21'
])
expect(manifests.map(manifest => manifest.namespace)).toEqual([
expect(manifests.map(manifest => manifest.namespace)).to.deep.equal([
'i18n',
'settings',
'io.ox/core/main'
])
expect(manifests.map(manifest => manifest.dependencies)).toEqual([
expect(manifests.map(manifest => manifest.dependencies)).to.deep.equal([
['io.ox/guidedtours/preload-helper-a7bbbf37.js'],
['io.ox/guidedtours/preload-helper-a7bbbf37.js', 'io.ox/guidedtours/i18n.3de05d46.js'],
['io.ox/guidedtours/preload-helper-a7bbbf37.js', 'io.ox/guidedtours/i18n.3de05d46.js']
......
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from '@jest/globals'
import mockfs from 'mock-fs'
import request from 'supertest'
import { createApp } from '../src/createApp'
import { createMockServer, generateSimpleViteManifest, getRandomPort } from './util.js'
import { createApp } from '../src/createApp.js'
import { createMockServer, generateSimpleViteManifest, getRandomPort, mockConfig } from './util.js'
import { expect } from 'chai'
describe('Responses contain custom headers', () => {
const port = getRandomPort()
describe('Responses contain custom headers', function () {
let app
let mockserver
const port = getRandomPort()
let restoreConfig
beforeAll(() => {
mockfs({
'./config': {
'config.yaml': `baseUrls:
- http://localhost:${port}`
}
})
before(function () {
;({ restore: restoreConfig } = mockConfig({ urls: [`http://localhost:${port}/`] }))
app = createApp()
})
afterAll(() => {
mockfs.restore()
after(function () {
restoreConfig()
})
beforeEach(async () => {
beforeEach(async function () {
mockserver = await createMockServer({ port })
mockserver.respondWith({
'/manifest.json': generateSimpleViteManifest({
......@@ -35,21 +31,21 @@ describe('Responses contain custom headers', () => {
await request(app).get('/ready')
})
afterEach(() => {
afterEach(function () {
mockserver.close()
delete process.env.APP_VERSION
delete process.env.BUILD_TIMESTAMP
delete process.env.CI_COMMIT_SHA
})
it('has own metadata', async () => {
it('has own metadata', async function () {
process.env.APP_VERSION = '4.2'
process.env.BUILD_TIMESTAMP = '0123456789'
process.env.CI_COMMIT_SHA = '0123456789abcdef'
const response = await request(app).get('/meta')
expect(response.statusCode).toBe(200)
expect(response.body).toContainEqual({
expect(response.statusCode).to.equal(200)
expect(response.body).to.deep.contain({
id: 'ui-middleware',
name: 'UI Middleware',
buildDate: '0123456789',
......@@ -58,21 +54,21 @@ describe('Responses contain custom headers', () => {
})
})
it('has metadata from another ui service if available', async () => {
it('has metadata from another ui service if available', async function () {
const response = await request(app).get('/meta')
expect(response.statusCode).toBe(200)
expect(response.body).toContainEqual({
expect(response.statusCode).to.equal(200)
expect(response.body).to.deep.contain({
name: 'sample-service',
version: '1.0'
})
})
it('does not have metadata from ui service when unavailable', async () => {
it('does not have metadata from ui service when unavailable', async function () {
await mockserver.close()
const response = await request(app).get('/meta')
expect(response.statusCode).toBe(200)
expect(response.body).not.toContain({
expect(response.statusCode).to.equal(200)
expect(response.body).to.not.deep.contain({
name: 'sample-service',
version: '1.0'
})
......
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from '@jest/globals'
import mockfs from 'mock-fs'
import request from 'supertest'
import { createApp } from '../src/createApp'
import { createMockServer, generateSimpleViteManifest, getRandomPort } from './util.js'
import { createApp } from '../src/createApp.js'
import { createMockServer, generateSimpleViteManifest, getRandomPort, mockConfig } from './util.js'
import { expect } from 'chai'
describe('UI Middleware', () => {
const port = getRandomPort()
const port2 = getRandomPort()
describe('UI Middleware', function () {
let app
let mockserver, mockserver2
const port = getRandomPort()
const port2 = getRandomPort()
beforeAll(() => {
mockfs({
'./config': {
'config.yaml': `baseUrls:
- http://localhost:${port}`
}
})
let restoreConfig
before(function () {
;({ restore: restoreConfig } = mockConfig({ urls: [`http://localhost:${port}/`] }))
app = createApp()
})
afterAll(() => {
mockfs.restore()
after(function () {
restoreConfig()
})
beforeEach(async () => {
beforeEach(async function () {
mockserver = await createMockServer({ port })
mockserver.respondWith({
'/manifest.json': generateSimpleViteManifest({ 'example.js': 'test' }),
......@@ -32,30 +28,30 @@ describe('UI Middleware', () => {
})
})
afterEach(() => {
mockserver?.close()
mockserver2?.close()
afterEach(async function () {
await mockserver?.close()
await mockserver2?.close()
process.env.CACHE_TTL = 30000
})
// Some say, this is not necessary to test
// But failing startups due to code errors in the probes will cause this to not work
// Therefore, we should keep this
it('is healthy', async () => {
it('is healthy', async function () {
const response = await request(app).get('/healthy')
expect(response.statusCode).toBe(200)
expect(response.statusCode).to.equal(200)
})
it('fetches manifest data', async () => {
it('fetches manifest data', async function () {
const response = await request(app).get('/manifests')
expect(response.statusCode).toBe(200)
expect(response.body).toEqual([{ namespace: 'test', path: 'example' }])
expect(response.statusCode).to.equal(200)
expect(response.body).to.deep.equal([{ namespace: 'test', path: 'example' }])
})
it('caches manifest data', async () => {
it('caches manifest data', async function () {
const response = await request(app).get('/manifests')
expect(response.statusCode).toBe(200)
expect(response.body).toEqual([{ namespace: 'test', path: 'example' }])
expect(response.statusCode).to.equal(200)
expect(response.body).to.deep.equal([{ namespace: 'test', path: 'example' }])
mockserver.close()
mockserver = await createMockServer({ port })
......@@ -67,17 +63,17 @@ describe('UI Middleware', () => {
await new Promise(resolve => setTimeout(resolve, 150))
const response2 = await request(app).get('/manifests')
expect(response2.statusCode).toBe(200)
expect(response2.body).toEqual([{ namespace: 'test', path: 'example' }])
expect(response2.statusCode).to.equal(200)
expect(response2.body).to.deep.equal([{ namespace: 'test', path: 'example' }])
})
it('refreshes manifest data after caching timeout', async () => {
it('refreshes manifest data after caching timeout', async function () {
process.env.CACHE_TTL = 1
app = createApp()
const response = await request(app).get('/manifests')
expect(response.statusCode).toBe(200)
expect(response.body).toEqual([{ namespace: 'test', path: 'example' }])
expect(response.statusCode).to.equal(200)
expect(response.body).to.deep.equal([{ namespace: 'test', path: 'example' }])
mockserver.close()
mockserver = await createMockServer({ port })
......@@ -90,18 +86,12 @@ describe('UI Middleware', () => {
await new Promise(resolve => setTimeout(resolve, 10))
const response2 = await request(app).get('/manifests')
expect(response2.statusCode).toBe(200)
expect(response2.body).toEqual([{ namespace: 'other', path: 'example' }])
expect(response2.statusCode).to.equal(200)
expect(response2.body).to.deep.equal([{ namespace: 'other', path: 'example' }])
})
it('can load multiple configurations', async () => {
mockfs({
'./config': {
'config.yaml': `baseUrls:
- http://localhost:${port}
- http://localhost:${port2}`
}
})
it('can load multiple configurations', async function () {
;({ restore: restoreConfig } = mockConfig({ urls: [`http://localhost:${port}/`, `http://localhost:${port2}`] }))
mockserver.close()
mockserver = await createMockServer({ port })
......@@ -121,8 +111,8 @@ describe('UI Middleware', () => {
await request(app)
.get('/manifests')
.then(response => {
expect(response.statusCode).toBe(200)
expect(response.body).toEqual([
expect(response.statusCode).to.equal(200)
expect(response.body).to.deep.equal([
{ namespace: 'other', path: 'example1' },
{ namespace: 'thing', path: 'example2' }
])
......
import express from 'express'
import config from '../src/config.js'
export function getRandomPort () {
return 1000 + (Math.random() * 39000) >> 0
......@@ -32,3 +33,16 @@ export function generateSimpleViteManifest (mapping) {
}
return viteManifest
}
export function mockConfig ({ urls = [] } = {}) {
const prevLoad = config.load
config.load = async () => {}
config._urls = urls
// return a restore
return {
restore () {
config.load = prevLoad
delete config._urls
}
}
}
import { describe, it, expect } from '@jest/globals'
import { hash } from '../src/util'
import { generateSimpleViteManifest } from './util'
import { hash } from '../src/util.js'
import { generateSimpleViteManifest } from './util.js'
import { expect } from 'chai'
describe('Util', function () {
describe('hash function', function () {
......@@ -9,7 +9,7 @@ describe('Util', function () {
'example.js': { imports: ['test.css'] },
'test.css': { }
})
expect(hash(manifest)).toEqual('2245696177')
expect(hash(manifest)).to.equal('2245696177')
})
it('the hash changes when the manifest changes', function () {
......@@ -22,9 +22,9 @@ describe('Util', function () {
'test1.css': { }
})
expect(hash(manifest)).not.toEqual(hash(manifestChanged))
expect(hash(manifest)).toEqual('2245696177')
expect(hash(manifestChanged)).toEqual('2547998666')
expect(hash(manifest)).not.to.equal(hash(manifestChanged))
expect(hash(manifest)).to.equal('2245696177')
expect(hash(manifestChanged)).to.equal('2547998666')
})
})
})
source diff could not be displayed: it is too large. Options to address this: view the blob.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment