Javascript 导入'spyOn'函数以摆脱';未定义';埃斯林特误差
我有一个单元测试,它使用Javascript 导入'spyOn'函数以摆脱';未定义';埃斯林特误差,javascript,unit-testing,jestjs,eslint,Javascript,Unit Testing,Jestjs,Eslint,我有一个单元测试,它使用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("s
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();
});
从“React”导入React;
从“jest matchers”导入expect;
从“../PointsAwardingPage”导入PointsAwardingPage;
从“../children/PointsAwardingForm”导入PointsAwardingForm;
从“酶”导入{shall};
它(“应该调用表单中的change方法”,()=>{
//给定
spyOn(PointsAwardingPage.prototype,'change')。和.callThrough();
const form=shallow().find('PointsAwardingForm');
//什么时候
form.props().onChange();
//然后
expect(PointsAwardingPage.prototype.change).toHaveBeenCalled();
});
一切正常。但是,我看到以下关于spyOn
函数调用的eslint
错误消息
未定义spyOn(无未定义)
为了消除此错误,我可以使用哪个
import
语句?这是因为spyOn
是由测试环境提供的-在您的例子中是Jest-因此它不是由您定义的
ESLint只在代码中查找定义
摆脱它的一种简单而安全的方法是在测试文件的顶部放置一条注释
/*global spyOn*/
,它告诉ESLint您已经定义了它,而实际上并没有这样做 虽然global
注释是一个有效的解决方案,但我相信您可以简单地使用jest.spyOn()
别忘了在中定义jest
。eslintrc
:
"env": {
"jest": true
}
哦,我不知道-这个自动“定义”jest的globals等是否适合你?@NicholasKyriakides确切地说()现在我在这样做后得到了这个错误<代码>类型错误:无法读取未定义的属性“callThrough”我不知道这样的语法,但间谍将携带原始实现(类似于Jasmine的
callThrough
)