Insert(SpyOn 2 times) jQuery value to input during Jasmine tests

倖福魔咒の 提交于 2020-01-17 06:35:11

问题


Hi i have a works tests

it("should add a model", function() {

    spyOn($.fn, "val").and.returnValue("Bar");

    foodtype.addNewFoodtype(); //My view 
    expect($("#newFoodtype").val()).toEqual("Bar");
    expect(foodtype.collection.length).toEqual(1);

});

on next test when I set

spyOn($.fn, "val").and.returnValue("Bar");
$("#newFoodtype").val()
spyOn($.fn, "val").and.returnValue("Foo");
$("#newFoodtype").val()

to checking a change but have a error

Error: spyOn : val has already been spied upon Usage: spyOn(object, methodName)


回答1:


  • You'll just need to return a new value instead of spying on it again.
  • Here is how I modified your code to make it work.
  • assigned a variable to spy so that I can access it once again spyObj.and.returnValue("Foo");
  • Please note that I've used a dummy view foodtype which mimics your view.

    var foodtype = {
      addNewFoodtype: function() {
        $("#newFoodtype").val("some val");
        this.collection.push("some val");
      },
      collection: []
    }
    describe("multispy demo", function() {
      it("should add a model", function() {
        var spyObj = spyOn($.fn, "val").and.returnValue("Bar");
        foodtype.addNewFoodtype(); //My view 
        expect($("#newFoodtype").val()).toEqual("Bar");
        expect(foodtype.collection.length).toEqual(1);
        spyObj.and.returnValue("Foo");
        expect($("#newFoodtype").val()).toEqual("Foo");
      });
    
    });
    


来源:https://stackoverflow.com/questions/42084022/insertspyon-2-times-jquery-value-to-input-during-jasmine-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!