如何调用方法进行测试而不执行?

问题描述

这是我的组件:

@Component({
    selector: 'app-signup',templateUrl: './signup.component.html',styleUrls: ['./signup.component.scss']
})
export class SignUpComponent implements OnInit {
    specialLink: string;

    constructor( 
        private activatedRoute: ActivatedRoute,private techService: TechService
 ) {}

ngOnInit() {
        this.specialLink = this.activatedRoute.snapshot.params.id;

        if (this.specialLink !== undefined) {
            console.log('GOOD1');
            this.setSpecialSignup();
            console.log('GOOD3');
        }

setSpecialSignup() {
        console.log('GOOD2');
        this.techService.getStuff();
    }

这是我的测试:

describe('SignUpComponent',() => {
  let component: SignUpComponent;
  let fixture: ComponentFixture<SignUpComponent>;
  let ActivatedRouteMock: any;
  
  beforeEach(async(() => {
    ActivatedRouteStub = {
      snapshot: {
        params: { id: 123 }
      },};

    TechServiceMock = jasmine.createSpyObj('TechService',['getStuff']);
    TechServiceMock.getStuff.and.returnValue(new Promise((resolve,reject) => { resolve() }));

    TestBed.configureTestingModule({
      declarations: [ SignUpComponent ],imports: [ RouterTestingModule ],providers: [
        {provide: ActivatedRoute,useValue: ActivatedRouteStub},{provide: TechService,useValue: TechServiceMock},]
    })
    .compileComponents();
  }));

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


  describe('to get special signup',() => {
      it('should call setSpecialSignup() one time when user is coming from special link',() => {
        spyOn(component,'setSpecialSignup');
        ActivatedRouteStub.snapshot.params.id = "some_special_link";
        fixture.detectChanges();
        expect(component.setSpecialSignup).toHaveBeenCalled(); // it's working
      });

      it('should call TechService',() => {
        ActivatedRouteStub.snapshot.params.id = "123";
        fixture.detectChanges();
        expect(TechServiceMock.getStuff).toHaveBeenCalled(); // it's NOT working
      });
    });

我想测试是否已调用techService.getStuff()。服务在 注册组件中的setSpecialSignup()方法。

该方法在我测试时已被调用,但控制台中的日志告诉我否则。 (它进入GOOD1和GOOD3而没有GOOD2,这很奇怪。)

也许这是一个简单的问题,但是对此有什么建议吗? 如何测试TechServiceMock.getStuff()是否已被调用? 我尝试了不同的方法来模拟TechService,但是这些方法中的任何一种都可以。

我想念什么?

解决方法

如果我对您的理解正确,那么您正在寻找callThrough()方法,可以在这里了解更多信息:https://hatoum.com/blog/2016/11/12/jasmine-unit-testing-dont-forget-to-callthrough

相关问答

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