Jest createSpyObj

前端 未结 3 1180
青春惊慌失措
青春惊慌失措 2021-01-02 06:03

With Chai, you can create a spy object as follows:

chai.spy.object([ \'push\', \'pop\' ]);

With jasmine, you can use:

jasmi         


        
3条回答
  •  情歌与酒
    2021-01-02 06:29

    const video = {
      play() {
        return true;
      },
    };
    
    module.exports = video;
    

    And the test:

    const video = require('./video');
    
    test('plays video', () => {
      const spy = jest.spyOn(video, 'play');
      const isPlaying = video.play();
    
      expect(spy).toHaveBeenCalled();
      expect(isPlaying).toBe(true);
    
      spy.mockReset();
      spy.mockRestore();
    });
    

    Docs found here: https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname

    There is also jest.fn()

    const mockFn = jest.fn();
      mockFn();
      expect(mockFn).toHaveBeenCalled();
    
      // With a mock implementation:
      const returnsTrue = jest.fn(() => true);
      console.log(returnsTrue()); // true;
    

    https://facebook.github.io/jest/docs/en/jest-object.html#jestfnimplementation

提交回复
热议问题