Jasmine spyOn 多次返回 [英] Jasmine spyOn with multiple returns

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

问题描述

我想用 Jasmine 测试我的 Angular 应用程序.所以我创建了一些测试,其中大多数都可以正常工作.但是,我的一项功能要求用户填写提示.测试无法填充这个提示,所以我用 spyOn(window,'prompt').and.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 我想用 return '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天全站免登陆