【问题标题】:Import `spyOn` function to get rid of 'not defined' eslint error导入 `spyOn` 函数以摆脱“未定义”的 eslint 错误
【发布时间】:2017-09-28 03:32:56
【问题描述】:

我有一个使用来自jestspyOn 方法的单元测试。

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();
});

一切正常。但是,我看到以下关于spyOn 函数调用的eslint 错误消息。

spyOn is not defined (no-undef).

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

【问题讨论】:

    标签: javascript unit-testing jestjs eslint


    【解决方案1】:

    虽然global 评论是一个有效的解决方案,但我相信您可以简单地使用jest.spyOn()

    别忘了在.eslintrc 中定义jest

    "env": {
        "jest": true
    }
    

    【讨论】:

    • 哦不知道 - 这会自动为您“定义”笑话的全局变量等吗?
    • 现在我在这样做之后得到了这个错误。 TypeError: Cannot read property 'callThrough' of undefined
    • 我不知道 Jest 中有这样的语法,但是间谍会携带原始实现(类似于 Jasmine 的callThrough
    【解决方案2】:

    那是因为spyOn 是由测试环境提供的——在你的例子中是 Jest——因此它不是由你定义的。

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

    摆脱它的一种简单而安全的方法是在测试文件的顶部放置注释/*global spyOn*/,它告诉 ESLint 你已经定义了它,但实际上并没有这样做。

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2017-07-12
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多