简体   繁体   English

茉莉花间谍 callThrough 和 callFake

[英]Jasmine spies callThrough and callFake

I have a scenario whereby I want to call done() on a beforeEach after a callback has been invoked.我有一个场景,我想在调用回调之后在beforeEach上调用done()

I tried to do this as follows :我尝试这样做:

spyOn(scope, 'onAdmin').and.callThrough().and.callFake(function(){done()})

But I'm not sure I get the right behaviour.但我不确定我的行为是否正确。 Essentially what I want to achieve is to be able to call done() after each callback is done doing what it does.基本上我想要实现的是能够在每个回调完成后调用done()做它所做的。

UPDATE: workaround solution更新:变通解决方案

scope.onAdminBackup = scope.onAdmin;
spyOn(scope, 'onAdmin').and.callFake(function(admin)  {

 scope.onAdminBackup();
 done() ;

})  

I have never chained these kinds of functions together cuz in my mind they seem to do the opposite.我从来没有将这些类型的功能链接在一起,因为在我看来它们似乎正好相反。 You are saying when I call this method -onAdmin - in the scope call it as normal.您是说当我调用此方法时 -onAdmin - 在范围内正常调用它。 Which is what the callThrough method jasmine provides for us does.这就是 jasmine 为我们提供的 callThrough 方法所做的。

But then you are chaining along a callFake method as well so then you say but dont actually call it call this fake function instead - very conflicting.但是然后你也沿着一个 callFake 方法链接,所以你说但实际上并没有调用它而是调用这个假函数 - 非常矛盾。

If you want to call spy on the method onAdmin and instead of it being fired you want it to do something else - something mocked - then use the .and.callFake(fn).如果你想在 onAdmin 方法上调用 spy 而不是被触发,你希望它做其他事情 - 一些嘲笑 - 然后使用 .and.callFake(fn)。 Also take into account like @stefan above said - dont invoke the function - callFake is simply wanting a function as a parameter it will take care of calling it itself.还要考虑到像上面所说的@stefan - 不要调用函数 - callFake 只是想要一个函数作为参数,它会自己调用它。

This might be more along the lines of what you are looking for, if not show us some more code.如果没有向我们展示更多代码,这可能更符合您的要求。

spyOn(scope, 'onAdmin')and.callFake(done)

您在编写 done() 时立即调用 done() 尝试将 done 作为值传递:

spyOn(scope, 'onAdmin').and.callThrough().and.callFake(done)

I found a work around way to do this.我找到了一种解决方法来做到这一点。 Jasmine has a method called addSpyStategy where you can add a custom strategy like callThrough or callFake. Jasmine 有一个名为 addSpyStategy 的方法,您可以在其中添加自定义策略,例如 callThrough 或 callFake。 It would look something like this:它看起来像这样:

jasmine.addSpyStrategy('callThroughAndThen', (spy, fn) => {
  return function() {
    spy.and.callThrough();
    setTimeout(() => fn(...arguments), 0);
  }
});

the timeout makes sure the real function finishes before executing the custom function.超时确保真正的函数在执行自定义函数之前完成。 Then for your spy, you can do this:然后对于你的间谍,你可以这样做:

const spy = spyOn(scope, 'onAdmin')
 spy.and.callThroughAndThen(spy, () => {
  // your custom callback
  done();
});

note: make sure to put custom strategy in a beforeEach block注意:确保将自定义策略放在 beforeEach 块中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM