代码之家  ›  专栏  ›  技术社区  ›  vitaly-t

如何用笑话测试“this”调用上下文?

  •  0
  • vitaly-t  · 技术社区  · 8 年前

    如何测试 jest 调用一个函数 this

    我只能找到如何测试传入的参数 toHaveBeenCalledWith . 但它不能测试 上下文,我找不到任何其他API用于此或示例。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Brian Adams    8 年前

    开玩笑

    创建 mock mock.instances to check the value of this .

    test('the value of this using Jest', () => {
      const foo = {
        name: 'foo',
        func: function() {
          return `my name is ${this.name}`;
        }
      }
      const mockFunc = jest.spyOn(foo, 'func'); // spy on foo.func()
    
      expect(foo.func()).toBe('my name is foo');
      expect(mockFunc.mock.instances[0]).toBe(foo); // called on foo
    
      mockFunc.mockClear();
    
      const bar = {
        name: 'bar',
        func: foo.func // use the func from foo
      }
    
      expect(bar.func()).toBe('my name is bar');
      expect(mockFunc.mock.instances[0]).toBe(bar); // called on bar
    });
    

    西农

    Sinon 提供直接访问 thisValue .

    import * as sinon from 'sinon';
    
    test('the value of this using Sinon', () => {
      const foo = {
        name: 'foo',
        func: function() {
          return `my name is ${this.name}`;
        }
      }
      const spy = sinon.spy(foo, 'func'); // spy on foo.func()
    
      expect(foo.func()).toBe('my name is foo');
      expect(spy.lastCall.thisValue).toBe(foo); // called on foo
    
      const bar = {
        name: 'bar',
        func: foo.func // use the func from foo
      }
    
      expect(bar.func()).toBe('my name is bar');
      expect(spy.lastCall.thisValue).toBe(bar); // called on bar
    });