Files
renovate/tools/lint/rules/prefer-coerce-object.spec.ts
Sebastian Poxhofer c32e2391a0 refactor(linters): add prefer-coerce-object rule (#45493)
Refs #45216

The object counterpart to `prefer-coerce-array`: `x ?? {}` becomes
`coerceObject(x)`. The rule flags a `??` whose default is a bare `{}`
literal, so a populated default or an asserted `({} as Foo)` still
passes; a `x ?? y ?? {}` chain maps onto `coerceObject(x, y)`.

Every hit across `lib/` converted cleanly, so no disable comments were
needed.
2026-08-28 09:27:59 +00:00

54 lines
1.5 KiB
TypeScript

import { RuleTester } from 'oxlint/plugins-dev';
import rule from './prefer-coerce-object.ts';
RuleTester.describe = describe;
RuleTester.it = it;
const ruleTester = new RuleTester({
languageOptions: { parserOptions: { lang: 'ts' } },
});
ruleTester.run('prefer-coerce-object', rule, {
valid: [
// already using the helper
`const a = coerceObject(x);`,
// non-empty default
`const a = x ?? { a: 1 };`,
// asserted default is not a bare object literal
`const a = x ?? ({} as Foo);`,
// array default belongs to `prefer-coerce-array`
`const a = x ?? [];`,
// other logical operators
`const a = x || {};`,
`const a = x && {};`,
// assignment rather than a logical expression
`x ??= {};`,
// destructuring and parameter defaults have no helper form
`const { a = {} } = obj;`,
`function f(a = {}) {}`,
// empty object unrelated to a nullish default
`const a = {};`,
],
invalid: [
{
code: `const a = x ?? {};`,
errors: [{ messageId: 'preferCoerceObject' }],
},
// optional chaining operand
{
code: `const a = x?.y ?? {};`,
errors: [{ messageId: 'preferCoerceObject' }],
},
// call expression operand
{
code: `hasLockedUpdate(config, parse().workflows ?? {});`,
errors: [{ messageId: 'preferCoerceObject' }],
},
// chained nullish defaults report once, on the outer expression
{
code: `const a = x ?? y ?? {};`,
errors: [{ messageId: 'preferCoerceObject' }],
},
],
});