What is the difference between createspy and createspyobj

后端 未结 1 441
迷失自我
迷失自我 2020-12-13 01:21

I have used in my code like.

return $provide.decorator(\'aservice\', function($delegate) {
            $delegate.addFn = jasmine.createSpy().andReturn(true);         


        
相关标签:
1条回答
  • 2020-12-13 02:06

    jasmine.createSpy can be used when there is no function to spy on. It will track calls and arguments like a spyOn but there is no implementation.

    jasmine.createSpyObj is used to create a mock that will spy on one or more methods. It returns an object that has a property for each string that is a spy.

    If you want to create a mock you should use jasmine.createSpyObj. Check out the examples below.

    From the Jasmine documentation http://jasmine.github.io/2.0/introduction.html...

    createSpy:

    describe("A spy, when created manually", function() {
      var whatAmI;
    
      beforeEach(function() {
        whatAmI = jasmine.createSpy('whatAmI');
    
        whatAmI("I", "am", "a", "spy");
      });
    
      it("is named, which helps in error reporting", function() {
        expect(whatAmI.and.identity()).toEqual('whatAmI');
      });
    
      it("tracks that the spy was called", function() {
        expect(whatAmI).toHaveBeenCalled();
      });
    
      it("tracks its number of calls", function() {
        expect(whatAmI.calls.count()).toEqual(1);
      });
    
      it("tracks all the arguments of its calls", function() {
        expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
      });
    
      it("allows access to the most recent call", function() {
        expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
      });
    });
    

    createSpyObj:

    describe("Multiple spies, when created manually", function() {
      var tape;
    
      beforeEach(function() {
        tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']);
    
        tape.play();
        tape.pause();
        tape.rewind(0);
      });
    
      it("creates spies for each requested function", function() {
        expect(tape.play).toBeDefined();
        expect(tape.pause).toBeDefined();
        expect(tape.stop).toBeDefined();
        expect(tape.rewind).toBeDefined();
      });
    
      it("tracks that the spies were called", function() {
        expect(tape.play).toHaveBeenCalled();
        expect(tape.pause).toHaveBeenCalled();
        expect(tape.rewind).toHaveBeenCalled();
        expect(tape.stop).not.toHaveBeenCalled();
      });
    
      it("tracks all the arguments of its calls", function() {
        expect(tape.rewind).toHaveBeenCalledWith(0);
      });
    });
    
    0 讨论(0)
提交回复
热议问题