Jasmine测试中 spyOn、spyOnProperty、createSpy、createSpyObj


最近在给组件补充测试,顺便整理一下常用的测试方法 spyOn、spyOnProperty、createSpy、createSpyObj等的关键知识点。

spyOn

  • Jasmine 具有称为 spies 的双重测试功能。 spy可以存任何函数并跟踪对它的调用和所有参数。 spy仅存在于定义它的 describe 或 it 块中,并且在每个spec之后删除。
  • spyOn(obj: Object, methodName: string) → {Spy} 参数1:要安装spy的对象。参数2:要替换为 Spy 的方法的名称。返回值是一个Spy。
  • 以下示例包含toHaveBeenCalled、toHaveBeenCalledTimes、toHaveBeenCalledWith的使用。
// The example comes from Jasmine official 
describe("A spy", function() {
   
  var foo, bar = null;
  beforeEach(function() {
   
    foo = {
   
      setBar: function(value) {
   
        bar = value;
      }
    };
    
    spyOn(foo, 'setBar');   // const fooSpy = spyOn(foo, 'setBar');
    foo.setBar(123);
    foo.setBar(456, 'another param');
  });

  it("tracks that the spy was called", function() {
   
    expect(foo.setBar).toHaveBeenCalled();  // expect(fooSpy).toHaveBeenCalled();
  });

  it("tracks that the spy was called x times", function() {
   
    expect(foo.setBar).toHaveBeenCalledTimes(2);
  });

  it("tracks all the arguments of its calls", function() {
   
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
  });

  it("stops all execution on a function", function() {
   
    expect(bar).toBeNull();
  });

  it("tracks if it was called at all", function() {
   
    foo.setBar();
    expect(foo.setBar.calls.any()).toEqual(true);
  });
});

实际应用:

@Component({
   
    template: `
        <my-date-picker [ngModel]="value" (ngModelChange)="thyOnChange($event)"></my-date-picker>
    `
})
class MyTestComponent {
   
    value: Date | number;
    thyOnChange(): void {
   }
}

describe('test date picker component event via spy on', () => {
   
    let fixture: ComponentFixture<MyTestComponent>;
    let fixtureInstance: MyTestComponent;
    let debugElement: DebugElement;

    beforeEach(() => {
   
        TestBed.configureTestingModule({
   
            imports: [FormsModule, MyDatePickerModule],
            declarations: [MyTestComponent]<
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值