Skip to content

Commit

Permalink
fix(linter): bug in fixer for prefer-to-have-length (#5164)
Browse files Browse the repository at this point in the history
  • Loading branch information
shulaoda authored Aug 24, 2024
1 parent 01c0c3e commit 1f5b6b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
17 changes: 12 additions & 5 deletions crates/oxc_linter/src/rules/jest/prefer_to_have_length.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ impl PreferToHaveLength {
let Some(matcher) = parsed_expect_call.matcher() else {
return;
};

if expect_property_name != "length" || !is_equality_matcher(matcher) {
return;
}
Expand All @@ -161,12 +160,11 @@ impl PreferToHaveLength {
property_name: Option<&str>,
) -> String {
let mut formatter = fixer.codegen();
let Expression::Identifier(prop_ident) = mem_expr.object() else {
return formatter.into_source_text();
};

formatter.print_str("expect(");
formatter.print_str(prop_ident.name.as_str());
formatter.print_str(
fixer.source_range(Span::new(mem_expr.span().start, mem_expr.object().span().end)),
);
formatter.print_str(")");

if let Some(kind_val) = kind {
Expand Down Expand Up @@ -215,6 +213,10 @@ fn tests() {
("expect(files.length).toEqual(1);", None),
("expect(files.length).toStrictEqual(1);", None),
("expect(files.length).not.toStrictEqual(1);", None),
(
"expect((meta.get('pages') as YArray<unknown>).length).toBe((originalMeta.get('pages') as YArray<unknown>).length);",
None
),
];

let fix = vec![
Expand All @@ -240,6 +242,11 @@ fn tests() {
("expect(files.length).toEqual(1);", "expect(files).toHaveLength(1);", None),
("expect(files.length).toStrictEqual(1);", "expect(files).toHaveLength(1);", None),
("expect(files.length).not.toStrictEqual(1);", "expect(files).not.toHaveLength(1);", None),
(
"expect((meta.get('pages') as YArray<unknown>).length).toBe((originalMeta.get('pages') as YArray<unknown>).length);",
"expect((meta.get('pages') as YArray<unknown>)).toHaveLength((originalMeta.get('pages') as YArray<unknown>).length);",
None
),
];

Tester::new(PreferToHaveLength::NAME, pass, fail)
Expand Down
7 changes: 7 additions & 0 deletions crates/oxc_linter/src/snapshots/prefer_to_have_length.snap
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,10 @@ source: crates/oxc_linter/src/tester.rs
· ─────────────
╰────
help: Replace `expect(files.length).not.toStrictEqual` with `expect(files).not.toHaveLength`.

eslint-plugin-jest(prefer-to-have-length): Suggest using `toHaveLength()`.
╭─[prefer_to_have_length.tsx:1:55]
1expect((meta.get('pages') as YArray<unknown>).length).toBe((originalMeta.get('pages') as YArray<unknown>).length);
· ────
╰────
help: Replace `expect((meta.get('pages') as YArray<unknown>).length).toBe` with `expect((meta.get('pages') as YArray<unknown>)).toHaveLength`.

0 comments on commit 1f5b6b6

Please sign in to comment.