How to spyOn a value property (rather than a method) with Jasmine

前端 未结 10 2212
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 04:12

Jasmine\'s spyOn is good to change a method\'s behavior, but is there any way to change a value property (rather than a method) for an object? the code could be

相关标签:
10条回答
  • 2020-12-01 04:41

    Suppose there is a method like this that needs testing The src property of the tiny image needs checking

    function reportABCEvent(cat, type, val) {
                    var i1 = new Image(1, 1);
                    var link = getABC('creosote');
                        link += "&category=" + String(cat);
                        link += "&event_type=" + String(type);
                        link += "&event_value=" + String(val);
                        i1.src = link;
                    }
    

    The spyOn() below causes the "new Image" to be fed the fake code from the test the spyOn code returns an object that only has a src property

    As the variable "hook" is scoped to be visible in the fake code in the SpyOn and also later after the "reportABCEvent" is called

    describe("Alphabetic.ads", function() {
        it("ABC events create an image request", function() {
        var hook={};
        spyOn(window, 'Image').andCallFake( function(x,y) {
              hook={ src: {} }
              return hook;
          }
          );
          reportABCEvent('testa', 'testb', 'testc');
          expect(hook.src).
          toEqual('[zubzub]&arg1=testa&arg2=testb&event_value=testc');
        });
    

    This is for jasmine 1.3 but might work on 2.0 if the "andCallFake" is altered to the 2.0 name

    0 讨论(0)
  • 2020-12-01 04:43

    I'm a bit late to the party here i know but,

    You could directly access the calls object, which can give you the variables for each call

    expect(spy.calls.argsFor(0)[0].value).toBe(expectedValue)
    
    0 讨论(0)
  • 2020-12-01 04:46

    Jasmine doesn't have that functionality, but you might be able to hack something together using Object.defineProperty.

    You could refactor your code to use a getter function, then spy on the getter.

    spyOn(myObj, 'getValueA').andReturn(1);
    expect(myObj.getValueA()).toBe(1);
    
    0 讨论(0)
  • 2020-12-01 04:47

    You can not mock variable but you can create getter function for it and mock that method in your spec file.

    0 讨论(0)
提交回复
热议问题