Skip to content

Commit 156e022

Browse files
authored
test: prep for vitest 3 (#6822)
1 parent e818de2 commit 156e022

File tree

14 files changed

+84
-53
lines changed

14 files changed

+84
-53
lines changed

packages/cspell-io/src/VirtualFs.test.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -149,21 +149,21 @@ describe('VirtualFs', () => {
149149
test('try unsupported readFile', async () => {
150150
const fs = virtualFs.fs;
151151
const result = fs.readFile(new URL('ftp://example.com/data.json'));
152-
await expect(result).rejects.toEqual(new Error('Unsupported request: readFile'));
152+
await expect(result).rejects.toThrowError('Unsupported request: readFile');
153153
await expect(result).rejects.toBeInstanceOf(VFSErrorUnsupportedRequest);
154154
});
155155

156156
test('try unsupported stat', async () => {
157157
const fs = virtualFs.fs;
158158
const result = fs.stat(new URL('ftp://example.com/data.json'));
159-
await expect(result).rejects.toEqual(new Error('Unsupported request: stat'));
159+
await expect(result).rejects.toThrowError('Unsupported request: stat');
160160
await expect(result).rejects.toBeInstanceOf(VFSErrorUnsupportedRequest);
161161
});
162162

163163
test('try unsupported readDirectory', async () => {
164164
const fs = virtualFs.fs;
165165
const result = fs.readDirectory(new URL('ftp://example.com/data.json'));
166-
await expect(result).rejects.toEqual(new Error('Unsupported request: readDirectory'));
166+
await expect(result).rejects.toThrowError('Unsupported request: readDirectory');
167167
await expect(result).rejects.toBeInstanceOf(VFSErrorUnsupportedRequest);
168168
});
169169

packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.test.ts

+14-9
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ const urlIssues = new URL('issues/', pathRepoTestFixturesURL);
5757
const oc = <T>(obj: T) => expect.objectContaining(obj);
5858
const sm = (m: string | RegExp) => expect.stringMatching(m);
5959

60+
function expectError(err: string | Error) {
61+
const message = typeof err === 'string' ? err : err.message;
62+
return expect.objectContaining({ message });
63+
}
64+
6065
vi.mock('../../../util/logger');
6166

6267
const mockedLogError = vi.mocked(logError);
@@ -488,9 +493,9 @@ describe('Validate search/load config files', () => {
488493

489494
test.each`
490495
file | expectedConfig
491-
${samplesSrc} | ${readError(samplesSrc).error}
492-
${s('bug-fixes')} | ${readError(s('bug-fixes')).error}
493-
${s('js-config/cspell-bad.js')} | ${readError(s('js-config/cspell-bad.js')).error}
496+
${samplesSrc} | ${expectError(readError(samplesSrc).error)}
497+
${s('bug-fixes')} | ${expectError(readError(s('bug-fixes')).error)}
498+
${s('js-config/cspell-bad.js')} | ${expectError(readError(s('js-config/cspell-bad.js')).error)}
494499
`('readConfigFile with error $file', async ({ file, expectedConfig }: TestLoadConfig) => {
495500
await expect(readConfigFile(file)).rejects.toEqual(expectedConfig);
496501
expect(mockedLogWarning).toHaveBeenCalledTimes(0);
@@ -502,9 +507,9 @@ describe('Validate search/load config files', () => {
502507
${samplesSrc} | ${readError(samplesSrc).error}
503508
${s('bug-fixes')} | ${readError(s('bug-fixes')).error}
504509
${s('js-config/cspell-bad.js')} | ${readError(s('js-config/cspell-bad.js')).error}
505-
`('ReadRawSettings with error $file', async ({ file, expectedConfig }: TestLoadConfig) => {
510+
`('ReadRawSettings with error $file', async ({ file, expectedConfig }) => {
506511
const result = await readRawSettings(file);
507-
expect(result).toEqual(oc({ __importRef: oc({ error: expectedConfig }) }));
512+
expect(result).toEqual(oc({ __importRef: oc({ error: expectError(expectedConfig) }) }));
508513
expect(mockedLogWarning).toHaveBeenCalledTimes(0);
509514
expect(mockedLogError).toHaveBeenCalledTimes(0);
510515
});
@@ -517,9 +522,9 @@ describe('Validate search/load config files', () => {
517522

518523
test.each`
519524
file | relativeTo | expectedConfig
520-
${samplesSrc} | ${undefined} | ${readError(samplesSrc).error}
521-
${s('bug-fixes')} | ${undefined} | ${readError(s('bug-fixes')).error}
522-
${s('bug-fixes/not-found/cspell.json')} | ${undefined} | ${readError(s('bug-fixes/not-found/cspell.json')).error}
525+
${samplesSrc} | ${undefined} | ${expectError(readError(samplesSrc).error)}
526+
${s('bug-fixes')} | ${undefined} | ${expectError(readError(s('bug-fixes')).error)}
527+
${s('bug-fixes/not-found/cspell.json')} | ${undefined} | ${expectError(readError(s('bug-fixes/not-found/cspell.json')).error)}
523528
${s('dot-config/.config/cspell.config.yaml')} | ${undefined} | ${oc(cf(s('dot-config/.config/cspell.config.yaml'), oc({ name: 'Nested in .config' })))}
524529
${rp('cspell.config.json')} | ${undefined} | ${oc(cf(rp('cspell.config.json'), oc({ id: 'cspell-package-config' })))}
525530
${s('linked/cspell.config.js')} | ${undefined} | ${cf(s('linked/cspell.config.js'), oc({ description: 'cspell.config.js file in samples/linked' }))}
@@ -768,7 +773,7 @@ describe('ConfigLoader with VirtualFS', () => {
768773

769774
expect(configFile).toBeInstanceOf(Error);
770775
assert(configFile instanceof Error);
771-
expect(configFile.cause).toEqual(new Error(`Untrusted URL: "${location?.href}"`));
776+
expect(configFile.cause).toEqual(expectError(`Untrusted URL: "${location?.href}"`));
772777
});
773778
});
774779

packages/cspell-lib/src/lib/spellCheckFile.test.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { extendExpect } from '../test-util/test.matchers.mjs';
1212
import type { Document } from './Document/index.js';
1313
import { fileToDocument, fileToTextDocument } from './Document/resolveDocument.js';
1414
import type { CSpellSettingsInternal } from './Models/CSpellSettingsInternalDef.js';
15-
import { ImportError } from './Settings/Controller/ImportError.js';
1615
import type { SpellCheckFileOptions, SpellCheckFileResult } from './spellCheckFile.js';
1716
import { determineFinalDocumentSettings, spellCheckDocument, spellCheckFile } from './spellCheckFile.js';
1817
import * as Uri from './util/Uri.js';
@@ -278,7 +277,7 @@ function tf(file: string) {
278277
}
279278

280279
function err(msg: string): Error {
281-
return new ImportError(msg);
280+
return new Error(msg);
282281
}
283282

284283
function errNoEnt(file: string): Error {

packages/cspell-lib/src/lib/util/errors.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ describe('errors', () => {
6060
test.each`
6161
err | expected
6262
${new Error('hello')} | ${new Error('hello')}
63-
${'hello'} | ${new Error('hello')}
63+
${'hello'} | ${new UnknownError('hello')}
6464
${'hello'} | ${expect.any(UnknownError)}
6565
`('toError', ({ err, expected }) => {
6666
expect(toError(err)).toEqual(expected);

packages/cspell-service-bus/src/SystemServiceBus.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,8 @@ describe('SystemServiceBus Behavior', () => {
7676
${RequestFsReadFile.create({ uri: 'file://my_file.txt' })} | ${{ value: 'read file: file://my_file.txt' }}
7777
${RequestFsReadFile.create({ uri: 'https://www.example.com/my_file.txt' })} | ${{ value: 'fetch http: https://www.example.com/my_file.txt' }}
7878
${RequestFsReadFile.create({ uri: 'https://www.example.com/my_dict.trie.gz' })} | ${{ value: 'Inflate: fetch http: https://www.example.com/my_dict.trie.gz' }}
79-
${{ type: 'zlib:compress' }} | ${{ error: new Error('Unhandled Request: zlib:compress') }}
80-
`('dispatch requests', ({ request, expected }) => {
79+
${{ type: 'zlib:compress' }} | ${{ error: expect.objectContaining({ message: 'Unhandled Request: zlib:compress' }) }}
80+
`('dispatch requests $request', ({ request, expected }) => {
8181
expect(serviceBus.dispatch(request)).toEqual(expected);
8282
});
8383
});

packages/cspell-service-bus/src/bus.test.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'vitest';
33
import { createServiceBus } from './bus.js';
44
import { createIsRequestHandler } from './createRequestHandler.js';
55
import type { Dispatcher } from './Dispatcher.js';
6+
import { ErrorServiceRequestDepthExceeded, ErrorUnhandledRequest, UnhandledHandlerError } from './errors.js';
67
import type { Handler } from './handlers.js';
78
import type { ServiceRequest, ServiceResponse } from './request.js';
89
import { createResponse as response, ServiceRequestCls } from './request.js';
@@ -95,9 +96,9 @@ describe('Service Bus', () => {
9596
${FibRequestFactory.create({ fib: 7 })} | ${response(13)}
9697
${StringLengthRequestFactory.create({ str: 'hello' })} | ${response(5)}
9798
${new StringToUpperRequest('hello')} | ${response('HELLO')}
98-
${new DoNotHandleRequest()} | ${{ error: new Error('Unhandled Request: Do Not Handle') }}
99-
${new RetryAgainRequest()} | ${{ error: new Error('Service Request Depth 10 Exceeded: Retry Again Request') }}
100-
${new ServiceRequestCls('throw', undefined)} | ${{ error: new Error('Unhandled Error in Handler: handlerThrowErrorOnRequest') }}
99+
${new DoNotHandleRequest()} | ${{ error: new ErrorUnhandledRequest(new DoNotHandleRequest()) }}
100+
${new RetryAgainRequest()} | ${{ error: new ErrorServiceRequestDepthExceeded(new RetryAgainRequest(), 10) }}
101+
${new ServiceRequestCls('throw', undefined)} | ${{ error: new UnhandledHandlerError('handlerThrowErrorOnRequest', undefined, 'error') }}
101102
`('serviceBus handle request: $request.type', ({ request, expected }) => {
102103
expect(bus.dispatch(request)).toEqual(expected);
103104
});

packages/cspell/src/app/cli-reporter.test.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Chalk } from 'chalk';
22
import { describe, expect, test } from 'vitest';
33

4+
import { ApplicationError } from './app.mjs';
45
import type { ReporterIssue } from './cli-reporter.js';
56
import { __testing__, checkTemplate } from './cli-reporter.js';
67

@@ -40,10 +41,10 @@ describe('cli-reporter', () => {
4041
template | expected
4142
${''} | ${true}
4243
${'{red $filename}'} | ${true}
43-
${'{red $filename'} | ${new Error('Chalk template literal is missing 1 closing bracket (`}`)')}
44-
${'{hello $filename}'} | ${new Error('Unknown Chalk style: hello')}
45-
${'{green.bold.underline $file}'} | ${new Error(`Unresolved template variable: '$file'`)}
46-
${'{green.bold.underline $file}:$rows:$col'} | ${new Error(`Unresolved template variables: '$file', '$rows'`)}
44+
${'{red $filename'} | ${new ApplicationError('Chalk template literal is missing 1 closing bracket (`}`)')}
45+
${'{hello $filename}'} | ${new ApplicationError('Unknown Chalk style: hello')}
46+
${'{green.bold.underline $file}'} | ${new ApplicationError(`Unresolved template variable: '$file'`)}
47+
${'{green.bold.underline $file}:$rows:$col'} | ${new ApplicationError(`Unresolved template variables: '$file', '$rows'`)}
4748
`('checkTemplate $template', ({ template, expected }) => {
4849
const r = checkTemplate(template);
4950
expect(r).toEqual(expected);

packages/cspell/src/app/lint/lint.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ export async function runLint(cfg: LintRequest): Promise<RunResult> {
174174
const fileInfo = prefetch?.fileInfo || (await readFileInfo(filename, undefined, true));
175175
if (fileInfo.errorCode) {
176176
if (fileInfo.errorCode !== 'EISDIR' && cfg.options.mustFindFiles) {
177-
const err = toError(`File not found: "${filename}"`);
177+
const err = new LinterError(`File not found: "${filename}"`);
178178
reporter.error('Linter:', err);
179179
result.errors += 1;
180180
}
@@ -754,3 +754,13 @@ async function writeDictionaryLog() {
754754
function globPattern(g: Glob) {
755755
return typeof g === 'string' ? g : g.glob;
756756
}
757+
758+
export class LinterError extends Error {
759+
constructor(message: string) {
760+
super(message);
761+
}
762+
763+
toString() {
764+
return this.message;
765+
}
766+
}

packages/cspell/src/app/util/cache/createCache.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from 'node:path';
44

55
import type { CacheSettings, CSpellSettings } from '@cspell/cspell-types';
66

7-
import { isError } from '../errors.js';
7+
import { isErrorLike } from '../errors.js';
88
import type { CacheOptions } from './CacheOptions.js';
99
import type { CSpellLintResultCache } from './CSpellLintResultCache.js';
1010
import { DiskCache } from './DiskCache.js';
@@ -75,7 +75,7 @@ async function resolveCacheLocation(cacheLocation: string): Promise<string> {
7575
if (s.isFile()) return cacheLocation;
7676
return path.join(cacheLocation, DEFAULT_CACHE_LOCATION);
7777
} catch (err) {
78-
if (isError(err) && err.code === 'ENOENT') {
78+
if (isErrorLike(err) && err.code === 'ENOENT') {
7979
return cacheLocation;
8080
}
8181
throw err;

packages/cspell/src/app/util/errors.test.ts

+15-14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect, test } from 'vitest';
22

3-
import { ApplicationError, CheckFailed, IOError, isError, toApplicationError, toError } from './errors.js';
3+
import { ApplicationError, CheckFailed, IOError, isErrorLike, toError } from './errors.js';
44

55
const oc = <T>(obj: T) => expect.objectContaining(obj);
66

@@ -24,33 +24,34 @@ describe('errors', () => {
2424
${null} | ${false}
2525
${'hello'} | ${false}
2626
`('isError $error', ({ error, expected }) => {
27-
expect(isError(error)).toBe(expected);
27+
expect(isErrorLike(error)).toBe(expected);
2828
});
2929

3030
test.each`
3131
error | expected
32-
${new CheckFailed('CheckFailed')} | ${new Error('CheckFailed')}
33-
${new ApplicationError('App Error')} | ${new Error('App Error')}
34-
${{ message: 'msg', name: 'error' }} | ${oc({ message: 'msg', name: 'error' })}
35-
${'hello'} | ${oc({ name: 'error', message: 'hello' })}
36-
${null} | ${oc({ name: 'error', message: 'null' })}
37-
${undefined} | ${oc({ name: 'error', message: 'undefined' })}
38-
${42} | ${oc({ name: 'error', message: '42' })}
39-
${{}} | ${oc({ name: 'error', message: '{}' })}
40-
${new IOError('io', { name: 'err', message: 'msg', code: 'ENOENT' })} | ${new Error('io')}
32+
${new CheckFailed('CheckFailed')} | ${new CheckFailed('CheckFailed')}
33+
${new ApplicationError('App Error')} | ${new ApplicationError('App Error')}
34+
${{ message: 'msg', name: 'error' }} | ${oc({ message: 'msg' })}
35+
${'hello'} | ${oc({ message: 'hello' })}
36+
${null} | ${oc({ message: 'null' })}
37+
${undefined} | ${oc({ message: 'undefined' })}
38+
${42} | ${oc({ message: '42' })}
39+
${{}} | ${oc({ message: '{}' })}
40+
${new IOError('io', { name: 'err', message: 'msg', code: 'ENOENT' })} | ${new IOError('io', { name: 'err', message: 'msg', code: 'ENOENT' })}
4141
`('toError $error', ({ error, expected }) => {
4242
expect(toError(error)).toEqual(expected);
4343
});
4444

4545
test.each`
4646
error | expected
47-
${new CheckFailed('CheckFailed')} | ${new Error('CheckFailed')}
48-
${new ApplicationError('App Error')} | ${new Error('App Error')}
47+
${new CheckFailed('CheckFailed')} | ${new CheckFailed('CheckFailed')}
48+
${new ApplicationError('App Error')} | ${new ApplicationError('App Error')}
4949
${{ message: 'msg', name: 'error' }} | ${new Error('msg')}
5050
${'hello'} | ${new Error('hello')}
5151
${{}} | ${new Error('{}')}
5252
`('toError $error', ({ error, expected }) => {
53-
expect(toApplicationError(error)).toEqual(expected);
53+
const e = toError(error);
54+
expect(e).toEqual(expected);
5455
});
5556

5657
test('IOError', () => {

packages/cspell/src/app/util/errors.ts

+10-5
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,20 @@ export class IOError extends ApplicationError {
3737

3838
export function toError(e: unknown): NodeError {
3939
if (isError(e)) return e;
40+
if (isErrorLike(e)) {
41+
const ex: NodeError = new Error(e.message, { cause: e });
42+
if (e.code !== undefined) ex.code = e.code;
43+
return ex;
44+
}
4045
const message = format(e);
41-
return {
42-
name: 'error',
43-
message,
44-
toString: () => message,
45-
};
46+
return new Error(message);
4647
}
4748

4849
export function isError(e: unknown): e is NodeError {
50+
return e instanceof Error;
51+
}
52+
53+
export function isErrorLike(e: unknown): e is NodeError {
4954
if (e instanceof Error) return true;
5055
if (!e || typeof e !== 'object') return false;
5156
const ex = <Error>e;

packages/cspell/src/app/util/reporters.test.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { CSpellReporter, ReporterSettings } from '@cspell/cspell-types';
22
import { MessageTypes } from '@cspell/cspell-types';
33
import { describe, expect, test, vi } from 'vitest';
44

5+
import { ApplicationError } from './errors.js';
56
import { InMemoryReporter } from './InMemoryReporter.js';
67
import { loadReporters, mergeReporters } from './reporters.js';
78

@@ -42,7 +43,7 @@ describe('mergeReporters', () => {
4243

4344
test.each`
4445
reporter | expected
45-
${['@cspell/cspell-json-reporter', false]} | ${new Error('Failed to load reporter @cspell/cspell-json-reporter: cspell-json-reporter settings must be an object')}
46+
${['@cspell/cspell-json-reporter', false]} | ${new ApplicationError('Failed to load reporter @cspell/cspell-json-reporter: cspell-json-reporter settings must be an object')}
4647
${['@cspell/cspell-unknown-reporter']} | ${oc({ message: sc("Failed to load reporter @cspell/cspell-unknown-reporter: Cannot find package '@cspell/cspell-unknown-reporter' imported from") })}
4748
${'@cspell/cspell-unknown-reporter'} | ${oc({ message: sc("Failed to load reporter @cspell/cspell-unknown-reporter: Cannot find package '@cspell/cspell-unknown-reporter'") })}
4849
`('loadReporters fail $reporter', async ({ reporter, expected }) => {

test-packages/cspell-service-bus/test-cspell-service-bus-esm/src/index.test.mts

+7-3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ import {
1111
StringToUpperRequest,
1212
} from './index.mjs';
1313

14+
function expectError(message: string) {
15+
return { error: expect.objectContaining({ message }) };
16+
}
17+
1418
describe('Service Bus', () => {
1519
const bus = createBus();
1620

@@ -21,9 +25,9 @@ describe('Service Bus', () => {
2125
${FibRequestFactory.create({ fib: 7 })} | ${createResponse(13)}
2226
${StringLengthRequestFactory.create({ str: 'hello' })} | ${createResponse(5)}
2327
${new StringToUpperRequest('hello')} | ${createResponse('HELLO')}
24-
${new DoNotHandleRequest()} | ${{ error: new Error('Unhandled Request: Do Not Handle') }}
25-
${new RetryAgainRequest()} | ${{ error: new Error('Service Request Depth 10 Exceeded: Retry Again Request') }}
26-
${new ServiceRequestCls('throw', undefined)} | ${{ error: new Error('Unhandled Error in Handler: handlerThrowErrorOnRequest') }}
28+
${new DoNotHandleRequest()} | ${expectError('Unhandled Request: Do Not Handle')}
29+
${new RetryAgainRequest()} | ${expectError('Service Request Depth 10 Exceeded: Retry Again Request')}
30+
${new ServiceRequestCls('throw', undefined)} | ${expectError('Unhandled Error in Handler: handlerThrowErrorOnRequest')}
2731
`('serviceBus handle request: $request.type', ({ request, expected }) => {
2832
expect(bus.dispatch(request)).toEqual(expected);
2933
});

0 commit comments

Comments
 (0)