导入`spyOn`函数以摆脱未定义的'夹板错误

时间:2017-09-28 03:32:57

标签: javascript unit-testing jestjs eslint

我的单元测试使用spyOn中的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();
});

一切都运作良好。但是,我看到有关eslint函数调用的以下spyOn错误消息。

spyOn is not defined (no-undef)

我可以使用哪个import语句来消除此错误?

2 个答案:

答案 0 :(得分:5)

虽然global评论是有效的解决方案,但我相信您只需使用jest.spyOn()即可。

不要忘记在jest中定义.eslintrc

"env": {
    "jest": true
}

答案 1 :(得分:1)

那是因为spyOn是由测试环境提供的 - 在你的情况下是Jest - 因此它不是由你定义的。

ESLint仅在您的代码中查找定义。

一种简单而安全的方法就是在测试文件的顶部放置一条注释/*global spyOn*/,告诉ESLint你已经定义了它,而不是真正这样做。