【发布时间】:2020-05-28 17:55:08
【问题描述】:
我是 Angular 的新手。 我在学习Angular的TDD时遇到了一些问题。
据我所知,Testbed.configureTestingModule 的 TestModuleMetadata 是一个像 @ngModule 的对象一样具有提供者、声明和导入等的对象。
所以我想如果我想测试组件,我所要做的就是将组件放入 TestModuleMetaData 的提供者中。
但这带来了诸如“没有 SomeComponent 的提供者!”之类的错误。和 'StaticInjectorError[SomeComponent]: '
之后,我将 someComponent 从声明中移至提供者,并且它工作正常。
为什么会这样? 我认为声明是要在模块上使用的组件的数组,提供者是服务的。
我错了吗??
import { TestBed } from "@angular/core/testing";
import { WelcomeComponent } from "./welcome.component";
import { UserService } from "../user.service";
describe("WelcomeComponent", () => {
let comp: WelcomeComponent;
let userService: UserService;
beforeEach(() => {
// This work correctly
TestBed.configureTestingModule({
providers: [UserService, WelcomeComponent]
});
// This doesn't work
// TestBed.configureTestingModule({
// declarations: [WelcomeComponent],
// providers: [UserService]
// });
comp = TestBed.get(WelcomeComponent);
userService = TestBed.get(UserService);
});
it("should not have welcome message after construction", () => {
expect(comp.welcome).toBeUndefined();
});
it("should welcome logged in user after Angular calls ngOnInit", () => {
comp.ngOnInit();
expect(comp.welcome).toContain(userService.user.name);
});
it("should ask user to log in if not logged in after ngOnInit", () => {
userService.isLoggedIn = false;
comp.ngOnInit();
expect(comp.welcome).not.toContain(userService.user.name);
expect(comp.welcome).toContain("log in");
});
});
【问题讨论】:
-
你没看错,
declarations用于组件,providers用于服务。你能发布给你带来麻烦的代码吗? -
是的,我刚刚发布了我的代码,感谢您的关注
标签: angular karma-jasmine angular-test