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): implement no-test-prefixes #531

Merged
merged 4 commits into from
Jul 10, 2023
Merged
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
3 changes: 2 additions & 1 deletion crates/oxc_linter/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ oxc_macros::declare_all_lint_rules! {
typescript::no_unnecessary_type_constraint,
typescript::no_misused_new,
typescript::no_this_alias,
jest::no_disabled_tests
jest::no_disabled_tests,
jest::no_test_prefixes,
}

#[cfg(test)]
Expand Down
149 changes: 149 additions & 0 deletions crates/oxc_linter/src/rules/jest/no_test_prefixes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
use std::borrow::Borrow;

use oxc_ast::{AstKind, ast::Expression};
use oxc_diagnostics::{
miette::{self, Diagnostic},
thiserror::Error,
};
use oxc_macros::declare_oxc_lint;
use oxc_span::{Span, GetSpan};

use crate::{context::LintContext, rule::Rule, AstNode, jest_ast_util::{parse_jest_fn_call, ParsedJestFnCall, JestFnKind}, fixer::Fix};

#[derive(Debug, Error, Diagnostic)]
#[error("eslint(jest/no-test-prefixes): Use {0:?} instead.")]
#[diagnostic(severity(warning))]
struct NoTestPrefixesDiagnostic<'a>(&'a str, #[label] pub Span);

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

declare_oxc_lint!(
/// ### What it does
///
/// Require using `.only` and `.skip` over `f` and `x`.
///
/// ### Why is this bad?
///
/// Jest allows you to choose how you want to define focused and skipped tests,
/// with multiple permutations for each:
/// - only & skip: it.only, test.only, describe.only, it.skip, test.skip, describe.skip.
/// - 'f' & 'x': fit, fdescribe, xit, xtest, xdescribe.
///
/// This rule enforces usages from the only & skip list.
///
/// ### Example
/// ```javascript
/// fit('foo'); // invalid
/// fdescribe('foo'); // invalid
/// xit('foo'); // invalid
/// xtest('foo'); // invalid
/// xdescribe('foo'); // invalid
/// ```
NoTestPrefixes,
nursery
);

fn get_preferred_node_names(jest_fn_call: &ParsedJestFnCall) -> String {

let ParsedJestFnCall { members, raw, .. } = jest_fn_call;

let preferred_modifier = if raw.starts_with('f') {
"only"
} else {
"skip"
};
let member_names = members.iter().map(Borrow::borrow).collect::<Vec<&str>>().join(".");
let name_slice = &raw[1..];

if member_names.is_empty() {
format!("{name_slice}.{preferred_modifier}")
} else {
format!("{name_slice}.{preferred_modifier}.{member_names}")
}
}

impl Rule for NoTestPrefixes {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
if let AstKind::CallExpression(call_expr) = node.kind() {
if let Some(jest_fn_call) = parse_jest_fn_call(call_expr, ctx) {
let ParsedJestFnCall { kind, raw, .. } = &jest_fn_call;

if !matches!(kind, JestFnKind::Describe | JestFnKind::Test) {
return;
}

if !raw.starts_with('f') && !raw.starts_with('x') {
return;
}

let span = match &call_expr.callee {
Expression::TaggedTemplateExpression(tagged_template_expr) => {
tagged_template_expr.tag.span()
}
Expression::CallExpression(child_call_expr) => {
child_call_expr.callee.span()
}
_ => {
call_expr.callee.span()
}
};

let preferred_node_name = get_preferred_node_names(&jest_fn_call);
let preferred_node_name_cloned = preferred_node_name.clone();

ctx.diagnostic_with_fix(
NoTestPrefixesDiagnostic(Box::leak(preferred_node_name.into_boxed_str()), span),
|| Fix::new(preferred_node_name_cloned, span)
);
}
}
}
}

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

let pass = vec![
("describe('foo', function () {})", None),
("it('foo', function () {})", None),
("it.concurrent('foo', function () {})", None),
("test('foo', function () {})", None),
("test.concurrent('foo', function () {})", None),
("describe.only('foo', function () {})", None),
("it.only('foo', function () {})", None),
("it.each()('foo', function () {})", None),
("it.each``('foo', function () {})", None),
("test.only('foo', function () {})", None),
("test.each()('foo', function () {})", None),
("test.each``('foo', function () {})", None),
("describe.skip('foo', function () {})", None),
("it.skip('foo', function () {})", None),
("test.skip('foo', function () {})", None),
("foo()", None),
("[1,2,3].forEach()", None),
];

let fail = vec![
("fdescribe('foo', function () {})", None),
("xdescribe.each([])('foo', function () {})", None),
("fit('foo', function () {})", None),
("xdescribe('foo', function () {})", None),
("xit('foo', function () {})", None),
("xtest('foo', function () {})", None),
("xit.each``('foo', function () {})", None),
("xtest.each``('foo', function () {})", None),
("xit.each([])('foo', function () {})", None),
("xtest.each([])('foo', function () {})", None)
// TODO: Continue work on it when [#510](https://github.com/Boshen/oxc/issues/510) solved
cijiugechu marked this conversation as resolved.
Show resolved Hide resolved
// (r#"import { xit } from '@jest/globals';
// xit("foo", function () {})"#, None),
// (r#"import { xit as skipThis } from '@jest/globals';
// skipThis("foo", function () {})"#, None),
// (r#"import { fit as onlyThis } from '@jest/globals';
// onlyThis("foo", function () {})"#, None)
];

Tester::new(NoTestPrefixes::NAME, pass, fail).test_and_snapshot();
}
65 changes: 65 additions & 0 deletions crates/oxc_linter/src/snapshots/no_test_prefixes.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
source: crates/oxc_linter/src/tester.rs
expression: no_test_prefixes
---
⚠ eslint(jest/no-test-prefixes): Use "describe.only" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ fdescribe('foo', function () {})
· ─────────
╰────

⚠ eslint(jest/no-test-prefixes): Use "describe.skip.each" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xdescribe.each([])('foo', function () {})
· ──────────────
╰────

⚠ eslint(jest/no-test-prefixes): Use "it.only" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ fit('foo', function () {})
· ───
╰────

⚠ eslint(jest/no-test-prefixes): Use "describe.skip" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xdescribe('foo', function () {})
· ─────────
╰────

⚠ eslint(jest/no-test-prefixes): Use "it.skip" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xit('foo', function () {})
· ───
╰────

⚠ eslint(jest/no-test-prefixes): Use "test.skip" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xtest('foo', function () {})
· ─────
╰────

⚠ eslint(jest/no-test-prefixes): Use "it.skip.each" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xit.each``('foo', function () {})
· ────────
╰────

⚠ eslint(jest/no-test-prefixes): Use "test.skip.each" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xtest.each``('foo', function () {})
· ──────────
╰────

⚠ eslint(jest/no-test-prefixes): Use "it.skip.each" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xit.each([])('foo', function () {})
· ────────
╰────

⚠ eslint(jest/no-test-prefixes): Use "test.skip.each" instead.
╭─[no_test_prefixes.tsx:1:1]
1 │ xtest.each([])('foo', function () {})
· ──────────
╰────