如何在Angular中模拟父类方法进行单元测试?

问题描述

我正在为一个类编写单元测试,该类扩展了另一个类并在运行时调用父方法。由于我不想处理父类,有没有办法模拟该方法调用?我尝试了多种方法,但是没有任何作用

class A {
   doSomething(){
       console.log(123);
     }
}

class B extends A {
    work(){
      this.doSomething();
  }
}

如何模拟该函数调用并在B类的单元测试中返回其他内容?

我尝试了以下方法:

spyOn(b,'doSomething');

spyOn(Object.getPrototypeOf(b),'doSomething');

没有错误,只是不断调用原始父方法

解决方法

您可以做的,但我不建议您在类B中使用父方法本身。

我不推荐这种方法,因为您会在要进行单元测试的类中添加一些内容。我宁愿在此父方法中完成的工作都进行存根。

但是,如果您真的想存根该方法,则可以按照以下方式进行操作:

describe('DataService',() => {
    let service: DataService;

    beforeEach(async(() => {
      TestBed.configureTestingModule({ providers: [DataService] });
    }));

    beforeEach(() => {
      service = TestBed.get(DataService); // would be inject in newer angular versions
    });

    it('test case 2',() => {
      spyOn(service as any,'parentMethod').and.returnValue(5);
      expect(service.getData()).toEqual(5);
    });
});

DataService所在的位置


@Injectable({
  providedIn: 'root'
})
export class DataService extends AbstractDataService {
  constructor() {
    super();
   }

  getData() {
    return this.parentMethod();
  }
}

AbstractDataService

@Injectable({
  providedIn: 'root'
})
export class AbstractDataService {
  constructor() { }

  parentMethod() {
    console.log('parent method');
    return null;
  }
}

也适用于组件。但同样:不建议在被测对象内部模拟方法!

describe('AppComponent',() => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AppComponent,AbstractAppComponent],schemas: [NO_ERRORS_SCHEMA],bootstrap: [AppComponent]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
    });

    it('should mock method',() => {
      spyOn(component as any,'abstractMethod').and.returnValue(10);

      fixture.detectChanges();
      expect(component.myMethod()).toEqual(10);
    });    
});

Stackblitz with test cases for both service and component

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...