Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import `spyOn` function to get rid of 'not defined' eslint error

I have a unit test that uses spyOn method from jest.

import React from 'react';
import expect from 'jest-matchers';
import PointsAwardingPage from '../PointsAwardingPage';
import PointsAwardingForm from '../children/PointsAwardingForm';
import { shallow } from 'enzyme';

it("should call change method in form", () => {
  // given
  spyOn(PointsAwardingPage.prototype, 'change').and.callThrough();
  const form = shallow(<PointsAwardingPage />).find('PointsAwardingForm');

  // when
  form.props().onChange();

  // then
  expect(PointsAwardingPage.prototype.change).toHaveBeenCalled();
});

Everything works well. However, I see the following eslint error message regarding the spyOn function call.

spyOn is not defined (no-undef).

Which import statement can I use in order to get rid of this error?

like image 377
alayor Avatar asked Jan 04 '23 09:01

alayor


2 Answers

Although a global comment is a valid solution, I believe you could simply use jest.spyOn() instead.

Don't forget to define jest in your .eslintrc:

"env": {
    "jest": true
}
like image 97
Or B Avatar answered Jan 06 '23 00:01

Or B


That's because spyOn is provided by the test environment - in your case Jest - thus it's not defined by you.

ESLint looks for definitions in your code only.

An easy and safe way to get rid of it is to place a comment /*global spyOn*/ at the top of your test file, which tells ESLint that you have defined it, without actually doing so.

like image 42
nicholaswmin Avatar answered Jan 05 '23 22:01

nicholaswmin