问题描述
我想用 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 多次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)