【问题标题】:Jasmine Spy to return different values based on argumentJasmine Spy 根据参数返回不同的值
【发布时间】:2017-11-30 01:40:50
【问题描述】:

我正在监视一个 JS 方法。我想根据方法的实际参数返回不同的东西。我尝试了 callFake 并尝试使用 arguments[0] 访问参数,但它说 arguments[0] 未定义。 这是代码 -

 spyOn(testService, 'testParam').and.callFake(function() {
     var rValue = {};
     if(arguments[0].indexOf("foo") !== -1){
         return rValue;
     }
     else{
         return {1};
     }
 })        

这里建议 - Any way to modify Jasmine spies based on arguments?

但这对我不起作用。

【问题讨论】:

    标签: javascript jasmine spy


    【解决方案1】:

    使用参数应该可以正常工作。另外,您可以在测试中粘贴整个对象吗?尽管这不是问题的根源。

    这是我的使用方法。在行动中看到它here

    var testObj = {
      'sample': "This is a sample string",
      'methodUnderTest': function(param) {
        console.log(param);
        return param;
      }
    };
    
    testObj.methodUnderTest("You'll notice this string on console");
    
    describe('dummy Test Suite', function() {
      it('test param passed in', function() {
        spyOn(testObj, 'methodUnderTest').and.callFake(function() {
          var param = arguments[0];
          if (param === 5) {
            return "five";
          }
          return param;
        });
        var val = testObj.methodUnderTest(5);
        expect(val).toEqual('five');
        var message = "This string is not printed on console";
        val = testObj.methodUnderTest(message);
        expect(val).toEqual(message);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      相关资源
      最近更新 更多