您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

开玩笑的spyOn函数称为

开玩笑的spyOn函数称为

嗨,伙计,我知道我来晚了,但是除了您的方式之外,您几乎已经完成,没有任何改变spyOn。当您使用的间谍,你有两个选择:spyOnApp.prototype或组件component.instance()

将间谍附加到类原型上并渲染(浅渲染)实例的顺序很重要。

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

App.prototype第一行位有你需要的东西,使事情的工作。在class您使用实例化javascript new MyClass()或将其浸入之前,javascript 没有任何方法MyClass.prototype。对于您的特定问题,您只需监视该App.prototype方法myClickFn

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

方法要求a的shallow/render/mount实例React.Component可用。本质上spyOn就是在寻找可以劫持并推向市场的东西jest.fn()。它可能是:

平原object

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

class

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

一个React.Component instance

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

一个React.Component.prototype

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

我已经使用并看到了两种方法。当我有一个beforeEach()beforeAll()块时,我可能会采用第一种方法。如果我只需要快速监视,我将使用第二个。只需注意附加间谍的顺序即可。

编辑:如果要检查您的副作用,您myClickFn可以在单独的测试中调用它。

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/
其他 2022/1/1 18:16:29 有668人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶