【问题标题】:Jasmine spyOn with multiple returnsJasmine spyOn 多次返回
【发布时间】:2015-08-22 19:25:51
【问题描述】:

我想用 Jasmine 测试我的 Angular 应用程序。 所以我创建了一些测试,其中大多数都可以正常工作。 但是,我的一项功能要求用户填写提示。 测试无法填满这个提示,所以我用spyOn(window,'prompt').and.returnValue('test') 模拟了它们。这有效,但只有一次。

当我添加我的两个组件(提示所在的函数)时,我想spyOn 第一个提示的结果为“test”,第二个提示的结果为“test2”。我尝试这样做:

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')

但这会产生以下错误:Error: prompt has already been spied upon 这很合乎逻辑,但我不知道用 spyOn 返回的另一种方式。

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

【问题讨论】:

    标签: javascript angularjs coffeescript jasmine


    【解决方案1】:

    但这给出了以下错误:错误:提示已被 偷窥

    正确的做法是这样的:

    var spy = spyOn(window, 'prompt');
    
    ...
    spy.and.returnValue('test')
    
    ...
    spy.and.returnValue('test2')
    

    【讨论】:

      【解决方案2】:

      从 jasmine v2.5 开始,使用全局 allowRespy() 设置。

      jasmine.getEnv().allowRespy(true);

      当您不想和/或无法接触到第一个间谍时,您可以多次致电spyOn()。注意它会返回之前的间谍(如果有的话)。

      spyOn(window, 'prompt').and.returnValue('test')
      ...
      spyOn(window, 'prompt').and.returnValue('test')

      【讨论】:

        【解决方案3】:

        使用 spyOn 您可以返回模拟值并像下面的代码一样动态设置它

        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')
        

        【讨论】:

          猜你喜欢
          • 2016-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多