Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(linter): eslint-plugin-vitest/require-local-test-context-for-concurrent-snapshots #4796

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/oxc_linter/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,7 @@ mod vitest {
pub mod no_import_node_test;
pub mod prefer_to_be_falsy;
pub mod prefer_to_be_truthy;
pub mod require_local_test_context_for_concurrent_snapshots;
}

oxc_macros::declare_all_lint_rules! {
Expand Down Expand Up @@ -864,4 +865,5 @@ oxc_macros::declare_all_lint_rules! {
vitest::no_import_node_test,
vitest::prefer_to_be_falsy,
vitest::prefer_to_be_truthy,
vitest::require_local_test_context_for_concurrent_snapshots,
}
26 changes: 23 additions & 3 deletions crates/oxc_linter/src/rules/jest/valid_describe_callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,26 @@ fn run<'a>(possible_jest_node: &PossibleJestNode<'a, '_>, ctx: &LintContext<'a>)
return;
}

if call_expr.arguments.len() == 0 {
let arg_len = call_expr.arguments.len();

// Handle describe.todo("runPrettierFormat")
if ctx.frameworks().is_vitest() && arg_len == 1 {
if let Some(member_expr) = call_expr.callee.as_member_expression() {
let Some(property_name) = member_expr.static_property_name() else {
return;
};
if property_name == "todo" {
return;
}
}
}

if arg_len == 0 {
diagnostic(ctx, call_expr.span, Message::NameAndCallback);
return;
}

if call_expr.arguments.len() == 1 {
if arg_len == 1 {
// For better error notice, we locate it to arguments[0]
diagnostic(ctx, call_expr.arguments[0].span(), Message::NameAndCallback);
return;
Expand Down Expand Up @@ -353,7 +367,13 @@ fn test() {
("fdescribe(\"foo\", () => {})", None),
("describe.only(\"foo\", () => {})", None),
("describe.skip(\"foo\", () => {})", None),
("describe.todo(\"runPrettierFormat\");", None),
(
"
import { describe } from 'vitest';
describe.todo(\"runPrettierFormat\");
",
None,
),
(
"
describe('foo', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
use oxc_ast::{
ast::{BindingPatternKind, FormalParameters, PropertyKey},
AstKind,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_semantic::AstNode;
use oxc_span::Span;

use crate::{
context::LintContext,
rule::Rule,
utils::{
is_type_of_jest_fn_call, parse_expect_jest_fn_call, JestFnKind, JestGeneralFnKind,
PossibleJestNode,
},
};

fn require_local_test_context(span0: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("require local Test Context for concurrent snapshot tests".to_string())
.with_help("Use local Test Context instead")
.with_label(span0)
}

#[derive(Debug, Default, Clone)]
pub struct RequireLocalTestContextForConcurrentSnapshots;

declare_oxc_lint!(
/// ### Examples
///
/// ```javascript
/// // invalid
/// test.concurrent('myLogic', () => {
/// expect(true).toMatchSnapshot();
/// })
///
/// describe.concurrent('something', () => {
/// test('myLogic', () => {
/// expect(true).toMatchInlineSnapshot();
/// })
/// })
/// ```
///
/// ```javascript
/// // valid
/// test.concurrent('myLogic', ({ expect }) => {
/// expect(true).toMatchSnapshot();
/// })
///
/// test.concurrent('myLogic', (context) => {
/// context.expect(true).toMatchSnapshot();
/// })
/// ```
RequireLocalTestContextForConcurrentSnapshots,
style,
);

impl Rule for RequireLocalTestContextForConcurrentSnapshots {
fn run_once(&self, ctx: &LintContext) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we don't need to collect function parameters? We can iterate all expect call expression and combine you check method

https://github.com/veritem/eslint-plugin-vitest/blob/8b11357b8690c276b869a04140f5238679bab5de/src/rules/require-local-test-context-for-concurrent-snapshots.ts#L33

let mut function_args: Vec<String> = vec![];
let nodes = ctx.nodes();

for node in nodes.iter() {
if let AstKind::Function(func) = node.kind() {
Self::collect_functions_params(&func.params, &mut function_args);
} else if let AstKind::ArrowFunctionExpression(arrow_func) = node.kind() {
Self::collect_functions_params(&arrow_func.params, &mut function_args);
}
}

for node in nodes.iter() {
Self::check(node, &mut function_args, ctx);
}
}
}

impl RequireLocalTestContextForConcurrentSnapshots {
fn collect_functions_params(params: &FormalParameters, function_args: &mut Vec<String>) {
if !params.is_empty() {
for params in &params.items {
match &params.pattern.kind {
BindingPatternKind::BindingIdentifier(ident) => {
function_args.push(ident.name.to_string());
}
BindingPatternKind::ObjectPattern(obj_pat) => {
for prop in &obj_pat.properties {
if let PropertyKey::StaticIdentifier(ident) = &prop.key {
function_args.push(ident.name.to_string());
}
}
}
_ => (),
}
}
}
}

fn check<'a>(node: &AstNode<'a>, function_args: &mut [String], ctx: &LintContext<'a>) {
let AstKind::CallExpression(call_expr) = node.kind() else {
return;
};
let Some(callee_name) = call_expr.callee_name() else {
return;
};
let Some(expect_fn_call) =
parse_expect_jest_fn_call(call_expr, &PossibleJestNode { node, original: None }, ctx)
else {
return;
};

if function_args.contains(&expect_fn_call.name.to_string()) {
return;
}

if ![
"toMatchSnapshot",
"toMatchInlineSnapshot",
"toMatchFileSnapshot",
"toThrowErrorMatchingSnapshot",
"toThrowErrorMatchingInlineSnapshot",
]
.contains(&callee_name)
{
return;
}

let mut is_inside_sequential_describe_or_test = false;

for parent_node_id in ctx.nodes().ancestors(node.id()) {
let parent_node = ctx.nodes().get_node(parent_node_id);
if let AstKind::CallExpression(parent_call_expr) = parent_node.kind() {
if let Some(callee_name) = parent_call_expr.callee_name() {
let is_describe_or_test = is_type_of_jest_fn_call(
parent_call_expr,
&PossibleJestNode { node: parent_node, original: None },
ctx,
&[
JestFnKind::General(JestGeneralFnKind::Describe),
JestFnKind::General(JestGeneralFnKind::Test),
],
);

if is_describe_or_test
&& parent_call_expr.callee.is_member_expression()
&& callee_name.eq("concurrent")
{
is_inside_sequential_describe_or_test = true;
break;
}
}
}
}

if !is_inside_sequential_describe_or_test {
return;
}

ctx.diagnostic(require_local_test_context(call_expr.span));
}
}

#[test]
fn tests() {
use crate::tester::Tester;

let pass = vec![
(r#"it("something", () => { expect(true).toBe(true) })"#, None),
(r#"it.concurrent("something", () => { expect(true).toBe(true) })"#, None),
(r#"it("something", () => { expect(1).toMatchSnapshot() })"#, None),
(r#"it.concurrent("something", ({ expect }) => { expect(1).toMatchSnapshot() })"#, None),
(
r#"it.concurrent("something", ({ expect }) => { expect(1).toMatchInlineSnapshot("1") })"#,
None,
),
(
r#"describe.concurrent("something", () => { it("something", ({ expect }) => { expect(1).toMatchSnapshot() }) })"#,
None,
),
(
r#"describe.concurrent("something", () => { it("something", ({ expect }) => { expect(1).toMatchInlineSnapshot() }) })"#,
None,
),
(
r#"describe.concurrent("something", () => { it("something", () => { expect(true).toBe(true) }) })"#,
None,
),
(
r#"describe("something", () => { it("something", (context) => { context.expect(1).toMatchInlineSnapshot() }) })"#,
None,
),
(
r#"describe("something", () => { it("something", (context) => { expect(1).toMatchInlineSnapshot() }) })"#,
None,
),
(
r#"it.concurrent("something", (context) => { context.expect(1).toMatchSnapshot() })"#,
None,
),
];

let fail = vec![
(r#"it.concurrent("should fail", () => { expect(true).toMatchSnapshot() })"#, None),
(
r#"it.concurrent("should fail", () => { expect(true).toMatchInlineSnapshot("true") })"#,
None,
),
(
r#"
import { describe, expect, it } from 'vitest';
describe.concurrent("failing", () => { it("should fail", () => { expect(true).toMatchSnapshot() }) })
"#,
None,
),
(
r#"
import { describe, expect, it } from 'vitest';
describe.concurrent("failing", () => { it("should fail", () => { expect(true).toMatchInlineSnapshot("true") }) })
"#,
None,
),
(r#"it.concurrent("something", (context) => { expect(true).toMatchSnapshot() })"#, None),
(
r#"
it.concurrent("something", () => {
expect(true).toMatchSnapshot();
expect(true).toMatchSnapshot();
})
"#,
None,
),
(
r#"
it.concurrent("something", () => {
expect(true).toBe(true);
expect(true).toMatchSnapshot();
})
"#,
None,
),
(
r#"it.concurrent("should fail", () => { expect(true).toMatchFileSnapshot("./test/basic.output.html") })"#,
None,
),
(
r#"it.concurrent("should fail", () => { expect(foo()).toThrowErrorMatchingSnapshot() })"#,
None,
),
(
r#"it.concurrent("should fail", () => { expect(foo()).toThrowErrorMatchingInlineSnapshot("bar") })"#,
None,
),
];

Tester::new(RequireLocalTestContextForConcurrentSnapshots::NAME, pass, fail)
.with_vitest_plugin(true)
.test_and_snapshot();
}
Loading