ray-template/__test__/workspace/no-undefined.spec.ts
XiaoDaiGua-Ray 911c403434
feat: refine admin workflows for v6.0.3
Improve theme consistency, keyboard navigation, and reusable frontend components.
Harden fullstack initialization and expose scoped lint and Vitest commands.
2026-12-01 11:04:13 +08:00

86 lines
2.5 KiB
TypeScript

// @vitest-environment node
import { ESLint } from 'eslint'
const ruleId = 'ray-template/no-undefined'
const eslint = new ESLint({
fix: true,
ruleFilter: (rule) => rule.ruleId === ruleId,
overrideConfig: { languageOptions: { parserOptions: { project: false } } },
})
async function lint(source: string, extension = 'ts') {
const [result] = await eslint.lintText(source, {
filePath: `__test__/workspace/fixture.${extension}`,
})
expect(result.fatalErrorCount, result.messages[0]?.message).toBe(0)
return { code: result.output ?? source, messages: result.messages }
}
it.each([
[
'ts',
'let value: string | undefined = undefined\nvalue = undefined\nuse(undefined)\nvalue === undefined',
'let value: string | undefined = void 0\nvalue = void 0\nuse(void 0)\nvalue === void 0',
],
[
'ts',
'const options = { value: undefined, undefined }',
'const options = { value: void 0, undefined: void 0 }',
],
[
'tsx',
'const element = <Widget value={undefined} />',
'const element = <Widget value={void 0} />',
],
[
'vue',
'<script setup lang="ts">const value: undefined = undefined</script>',
'<script setup lang="ts">const value: undefined = void 0</script>',
],
[
'mjs',
'const result = []\nundefined?.method()',
'const result = []\n;(void 0)?.method()',
],
[
'mjs',
'if (enabled) undefined?.method()',
'if (enabled) (void 0)?.method()',
],
[
'mjs',
'const power = undefined ** 2\nconst result = new (undefined)()',
'const power = (void 0) ** 2\nconst result = new (void 0)()',
],
])('fixes runtime reads in %s from %s', async (extension, source, expected) => {
expect(await lint(source, extension)).toEqual({
code: expected,
messages: [],
})
})
it('preserves type keywords, type queries, literal keys, and member names', async () => {
const source =
'type Value = typeof undefined | undefined\n({ undefined: obj.undefined })'
expect(await lint(source)).toEqual({ code: source, messages: [] })
})
it.each([
['mjs', 'function read(undefined) { return undefined }'],
['mjs', 'undefined = 42'],
['cjs', 'delete undefined'],
['cjs', 'function read() { eval("var undefined = 42"); return undefined }'],
])('reports unsafe replacements in %s from %s', async (extension, source) => {
const { code, messages } = await lint(source, extension)
expect(code).toBe(source)
expect(messages.length).toBeGreaterThan(0)
expect(
messages.every((message) => message.ruleId === ruleId && !message.fix),
).toBe(true)
})