How do we clear spy programmatically in Jasmine?

后端 未结 10 2401
孤独总比滥情好
孤独总比滥情好 2020-12-15 02:11

How do we clear the spy in a jasmine test suite programmatically? Thanks.

beforeEach(function() {
  spyOn($, \"ajax\").andCallFake(function(params){
  })
})
         


        
10条回答
  •  庸人自扰
    2020-12-15 02:55

    I'm posting this answer to address the comment in OP @Tri-Vuong's code - which was my main reason for my visiting this page:

    I want to override the spy ... here and do it a little differently

    None of the answers so far address this point, so I'll post what I've learned and summarize the other answers as well.

    @Alissa called it correctly when she explained why it is a bad idea to set isSpy to false - effectively spying on a spy resulting in the auto-teardown behavior of Jasmine no longer functioning as intended. Her solution (placed within the OP context and updated for Jasmine 2+) was as follows:

    beforeEach(() => {
      var spyObj = spyOn(obj,'methodName').and.callFake(function(params){
      }) // @Alissa's solution part a - store the spy in a variable
    })
    
    it("should do the declared spy behavior", () => {
      // Act and assert as desired
    })
    
    it("should do what it used to do", () => {
      spyObj.and.callThrough(); // @Alissa's solution part b - restore spy behavior to original function behavior
      // Act and assert as desired
    })
    
    it("should do something a little differently", () => {
      spyObj.and.returnValue('NewValue'); // added solution to change spy behavior
      // Act and assert as desired
    })
    

    The last it test demonstrates how one could change the behavior of an existing spy to something else besides original behavior: "and-declare" the new behavior on the spyObj previously stored in the variable in the beforeEach(). The first test illustrates my use case for doing this - I wanted a spy to behave a certain way for most of the tests, but then change it for a few tests later.

    For earlier versions of Jasmine, change the appropriate calls to .andCallFake(, .andCallThrough(), and .andReturnValue( respectively.

提交回复
热议问题