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

[prefer-expect-assertions] allow beforeEach(expect.hasAssertions) #876

Open
EvgenyOrekhov opened this issue Aug 11, 2021 · 1 comment
Open

Comments

@EvgenyOrekhov
Copy link

Recently I found out that instead of repeating expect.hasAssertions() in each test, you can have a single beforeEach(expect.hasAssertions) call at the top of the file.

It would be great if prefer-expect-assertions could detect file-level beforeEach(expect.hasAssertions) call and NOT give warnings in this case.

Current behavior:

beforeEach(expect.hasAssertions);

test("foo", () => {
  // Warning: Every test should have either `expect.assertions(<number of assertions>)`
  // or `expect.hasAssertions()` as its first expression
});
beforeEach(() => {
  expect.hasAssertions();
  someOtherFunction();
});

test("foo", () => {
  // Warning: Every test should have either `expect.assertions(<number of assertions>)`
  // or `expect.hasAssertions()` as its first expression
});

Expected behavior:

beforeEach(expect.hasAssertions);

test("foo", () => {
  // No warnings
});
beforeEach(() => {
  expect.hasAssertions();
  someOtherFunction();
});

test("foo", () => {
  // No warnings
});
@G-Rath
Copy link
Collaborator

G-Rath commented Aug 13, 2021

I can do you one better: you can stick that beforeEach in a script to be called by jest via setupFilesAfterEnv - I do it in most of my projects when I'm just using expect.


Overall, I think I'm going to say "maybe" to this - I actually think we should get very close to being able to determine this, but have concerns over edge-cases and the complexity of the code it'd require.

Specifically, because we will have to track the nesting of each beforeEach relative to the test functions to cover i.e

describe('MyClass', () => {
  describe('#myMethod', () => {
    beforeEach(expect.hasAssertions);

    it('does something', () => {
      // ...
    });
  });

  describe('#myOtherMethod', () => {
    it('does something', () => {
      // ...
    });
  });
});

Still I think it might be possible based on some of the logic we have in other rules that do similar tracking of nesting that we might be able to do it.

@G-Rath G-Rath changed the title prefer-expect-assertions - allow beforeEach(expect.hasAssertions) [prefer-expect-assertions] allow beforeEach(expect.hasAssertions) Aug 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants