【发布时间】: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