【问题标题】:How can a method be called for testing and not be executed?如何调用方法进行测试而不执行?
【发布时间】:2020-08-14 14:19:30
【问题描述】:

这是我的组件:

@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,但其中任何一种都有帮助。

我错过了什么?

【问题讨论】:

    标签: angular typescript unit-testing service karma-jasmine


    【解决方案1】:

    如果我理解正确,您正在寻找 callThrough() 方法,您可以在此处阅读更多信息:https://hatoum.com/blog/2016/11/12/jasmine-unit-testing-dont-forget-to-callthrough

    【讨论】:

    • 完美!文章内容非常丰富,非常清晰,非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2018-07-16
    • 2019-02-10
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多