angular - TestBed 上的提供者和声明有什么区别
问题描述
我是 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");
});
});
解决方案
在您的测试代码中,您有:
comp = TestBed.get(WelcomeComponent);
那是为了查找已经实例化的服务。相反,您需要创建组件:
comp = TestBed.createComponent(WelcomeComponent);
推荐阅读
- laravel - 如果 php artisan serve 不起作用,如何更新 vue 组件?
- javascript - 在 AJAX 成功重新加载 DATATABLE 而不刷新页面
- excel - 在 Windows 任务计划程序中计划时如何通过 VBA 发送电子邮件?
- javascript - Object.is(x,y) 比其他比较快吗?
- javascript - LEAP YEAR 使用 JAVASCRIPT 验证 2104、2000、2100、2001 的输入
- grails - grails3中作为单例的服务范围
- database - 我可以输入不会保存在数据库中并且只在 selenium webdriver 中输入内存的数据(以任何形式)吗
- python-3.x - pymongo 3.8 不适用于 mondob 4 和 python 3.5
- php - 如何在 HTML 表中动态显示数据库表?
- html - 当我的弹出窗口处于活动状态时如何禁用页面背景上的滚动条