Files
privacy.sexy/tests/unit/shared/Assertions/ExpectThrowsError.ts
undergroundwires 5f11c8d98f Migrate unit/integration tests to Vitest with Vite
As part of transition to Vue 3.0 and Vite (#230), this commit
facilitates the shift towards building rest of the application using
Vite. By doing so, it eliminates reliance on outdated Electron building
system that offered limited control, blocking desktop builds (#233).

Changes include:

- Introduce Vite with Vue 2.0 plugin for test execution.
- Remove `mocha`, `chai` and other related dependencies.
- Adjust test to Vitest syntax.
- Revise and update `tests.md` to document the changes.
- Add `@modyfi/vite-plugin-yaml` plugin to be able to use yaml file
  depended logic on test files, replacing previous webpack behavior.
- Fix failing tests that are revealed by Vitest due to unhandled errors
  and lack of assertments.
- Remove the test that depends on Vue CLI populating `process.env`.
- Use `jsdom` for unit test environment, adding it to dependency to
  `package.json` as project now depends on it and it was not specified
  even though `package-lock.json` included it.
2023-08-22 14:02:35 +02:00

49 lines
1.6 KiB
TypeScript

import { expect } from 'vitest';
// `toThrowError` does not assert the error type (https://github.com/vitest-dev/vitest/blob/v0.34.2/docs/api/expect.md#tothrowerror)
export function expectThrowsError<T extends Error>(delegate: () => void, expected: T) {
// arrange
if (!expected) {
throw new Error('missing expected');
}
let actual: T | undefined;
// act
try {
delegate();
} catch (error) {
actual = error;
}
// assert
expect(Boolean(actual)).to.equal(true, `Expected to throw "${expected.name}" but delegate did not throw at all.`);
expect(Boolean(actual?.stack)).to.equal(true, 'Empty stack trace.');
expect(expected.message).to.equal(actual.message);
expect(expected.name).to.equal(actual.name);
expectDeepEqualsIgnoringUndefined(expected, actual);
}
function expectDeepEqualsIgnoringUndefined(expected: unknown, actual: unknown) {
const actualClean = removeUndefinedProperties(actual);
const expectedClean = removeUndefinedProperties(expected);
expect(expectedClean).to.deep.equal(actualClean);
}
function removeUndefinedProperties(obj: unknown): unknown {
return Object.keys(obj ?? {})
.reduce((acc, key) => {
const value = obj[key];
switch (typeof value) {
case 'object': {
const cleanValue = removeUndefinedProperties(value); // recurse
if (!Object.keys(cleanValue).length) {
return { ...acc };
}
return { ...acc, [key]: cleanValue };
}
case 'undefined':
return { ...acc };
default:
return { ...acc, [key]: value };
}
}, {});
}