导入 `spyOn` 函数以消除 'not defined' eslint 错误
Import `spyOn` function to get rid of 'not defined' eslint error
我有一个单元测试使用 jest
中的 spyOn
方法。
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
语句来消除此错误?
那是因为 spyOn
是由测试环境提供的 - 在您的情况下是 Jest - 因此它不是您定义的。
ESLint 仅在您的 代码中查找定义。
摆脱它的一种简单而安全的方法是在测试文件的顶部放置注释 /*global spyOn*/
,告诉 ESLint 您已经定义了它,但实际上并没有这样做。
虽然 global
评论是一个有效的解决方案,但我相信您可以简单地使用 jest.spyOn()
代替。
不要忘记在 .eslintrc
中定义 jest
:
"env": {
"jest": true
}
我有一个单元测试使用 jest
中的 spyOn
方法。
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
语句来消除此错误?
那是因为 spyOn
是由测试环境提供的 - 在您的情况下是 Jest - 因此它不是您定义的。
ESLint 仅在您的 代码中查找定义。
摆脱它的一种简单而安全的方法是在测试文件的顶部放置注释 /*global spyOn*/
,告诉 ESLint 您已经定义了它,但实际上并没有这样做。
虽然 global
评论是一个有效的解决方案,但我相信您可以简单地使用 jest.spyOn()
代替。
不要忘记在 .eslintrc
中定义 jest
:
"env": {
"jest": true
}