Jasmine spyOn有多个回报 [英] Jasmine spyOn with multiple returns

查看:146
本文介绍了Jasmine spyOn有多个回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Jasmine测试我的角度应用程序。
所以我创建了一些测试,其中大部分工作正常。
但是,我的一个功能要求用户填写提示。
测试无法填写此提示,因此我使用 spyOn(window,'prompt')和.returnValue('test')来模拟它们。这有效,但只有一次。

I would like to test my angular application with Jasmine. So I created some tests, most of them work fine. But, one of my functions require the user to fill in an prompt. Tests can not fill this prompt, so I mocked them with spyOn(window,'prompt').and.returnValue('test'). This works, but only once.

当我添加两个组件(提示所在的函数)时,我想要 spyOn 第一个结果为'test'的提示,第二个提示带有'test2'。我尝试按如下方式执行此操作:

When I add two of my components (the function in which the prompt is located), I want to spyOn the first prompt with result 'test', and the second prompt with 'test2'. I tried doing this as follows:

it 'should place the component as last object in the form', ->

      spyOn(window, 'prompt').and.returnValue('test')
      builder.addFormObject 'default', {component: 'test'}

      spyOn(window, 'prompt').and.returnValue('test2')
      builder.addFormObject 'default', {component: 'test2'}

      expect(builder.forms['default'][0].name).toEqual('test')

但是这给了以下错误:错误:提示已经被监视
这是合乎逻辑的,但我不知道用spyOn返回的另一种方式。

But this gives the following error: Error: prompt has already been spied upon This is quite logical, but I don't know another way of returning with a spyOn.

所以,我想要的是:
在第一个addFormObject之前,我想监视返回'test'的提示符。第二个addFormObject我想监视返回'test2'

So, what I want is this: Before the first addFormObject I want to spy on the prompt which returns 'test'. And the second addFormObject I want to spy with return 'test2'

推荐答案

使用spyOn你可以返回模拟值并动态设置它在以下代码中

With spyOn you can return mocked value and set it dynamically like in following code

it 'should place the component as last object in the form', ->
  mockedValue = null

      spyOn(window, 'prompt').and.returnValue(mockedValue)
      mockedValue = 'test'
      builder.addFormObject 'default', {component: 'test'}

      mockedValue = 'test2'
      builder.addFormObject 'default', {component: 'test2'}

      expect(builder.forms['default'][0].name).toEqual('test')

这篇关于Jasmine spyOn有多个回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆