I have MainComponent
that uses ChildComponentA
as a @ViewChild
. MainComponent
is calling a method on ChildComponentA
.
I want to write an unit test case mocking ChildComponentA
. How can I do this using TestBed
(in Angular 2 RC5)?
Before I used to use overrideDirective(MainComponentName, ChildComponentA, MockChildComponentA);
Is there an equivalent to this using TestBed
?
I tried using
TestBed.overrideComponent(ChildComponentA,{
set: {
template: '<div></div>'
}
});
Run Code Online (Sandbox Code Playgroud)
which just sets the template, but I want to mock the methods in …
试图TestBed
通过一个简单的例子在angular-2中学习这个测试实用程序并且击中了我的第一个拦截器.google或SO搜索没有产生任何匹配的示例,
所以,我有一个非常基本的组件header
如下 -
import { Component } from '@angular/core';
@Component({
selector: 'header',
template: ''
})
export class HeaderComponent{
public title: string;
constructor(testparam: string){
this.title = 'test';
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其规格如下 -
import { TestBed } from '@angular/core/testing';
import { HeaderComponent } from './header.component';
describe('HeaderComponent Test', () => {
let component: HeaderComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HeaderComponent]
});
const fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
});
it('should have the component defined', () => {
expect(component).toBeDefined();
});
it('should …
Run Code Online (Sandbox Code Playgroud) 我正在Angular应用程序中进行单元测试,我正在使用TestBed方法,
我正在测试组件,所以每个spec文件都是这样的
import...
describe('AppComponent', () => {
// Importing dependecies
beforeEach(async(() => {
TestBed.configureTestingModule({
imports : [RouterTestingModule , HttpModule , FormsModule ],
declarations: [AppComponent
],
providers: [AUTH_PROVIDERS ,UserService, SharedclientService, RouteNavigator, JwtHelper, ReloadTokenService, ShopService
, EnvVarsService, ProfileService, LocalStorageService, ApiVersionInterceptor, ApiTrackingInterceptor, MonitoringService ,
{ provide: 'LOCAL_STORAGE_SERVICE_CONFIG', useValue: userConfig } , TokenUtilService , HttpInterceptorService ,
{ provide: InterceptableStoreFactory, useClass: InterceptableStoreFactoryMock },ReloadTokenEventService , InterceptableStoreFactory
]
}).compileComponents();
}));
// detecting changes every times
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
// …
Run Code Online (Sandbox Code Playgroud) 我正在从 Angular 8.0 升级到 Angular 9.1.1。通过一些工作,一切都可以正常构建并运行。我遇到了本地化问题https://angular.io/guide/migration-localize并遵循了这些说明 - 这使我的项目能够构建和运行!但是,当我运行测试(业力/茉莉花)时,我仍然遇到这个问题
我使用 CLI 来升级我的项目。我似乎找不到任何其他迁移本地化所需的步骤。
我正在使用 TestBed 进行单元测试,但在调用 时失败TestBed.createComponent
,抛出错误:
Error: It looks like your application or one of its dependencies is using i18n.
Angular 9 introduced a global `$localize()` function that needs to be loaded.
Please run `ng add @angular/localize` from the Angular CLI.
(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.
For server-side rendering applications add the import to your `main.server.ts` file.)
Run Code Online (Sandbox Code Playgroud)
失败测试组件模板中的一段 HTML 示例是:
<span i18n> …
Run Code Online (Sandbox Code Playgroud) 我需要测试我的服务,该服务用于Injector
注入服务而不是constructor()
.
我使用这种方式的主要原因是大量的服务扩展了我的共同点SimpleDataService
。这里有CompanyService
,等等,大家都扩展SimpleDataService ProductService
。TagService
所以我不想为super()
调用定义超过必要的参数。
应用程序模块.ts
import { Injector, NgModule } from '@angular/core';
export let InjectorInstance: Injector;
@NgModule({
// ...
})
export class AppModule {
constructor(private injector: Injector) {
InjectorInstance = this.injector;
}
}
Run Code Online (Sandbox Code Playgroud)
简单数据.service.ts
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { InjectorInstance } from 'src/app/app.module';
import { PaginateInterface } from 'src/app/models/paginate/paginate.interface';
import { environment } …
Run Code Online (Sandbox Code Playgroud) 我正在将仅使用 jest 的组件单元测试迁移到使用 Testbed 和 jest 的 UI 测试(在我仅使用 jest 进行单元测试之前component = new MyCompontent()
)。
我正在使用 Angular 11。
有件事我不明白compileComponents
。在文档中,它说“如果您只使用 CLI ng test 命令运行测试,则可以忽略此部分,因为 CLI 在运行测试之前编译应用程序。”
我没有打电话ng test
,但jest --watch
我的测试无论有没有都有效compileComponents
(我所说的工作是指它们正确地断言了我的观点)。
还有一个“如果任何测试模块组件具有 templateUrl 或 styleUrls,则必须调用此方法,因为获取组件模板和样式文件必然是异步的”
我的组件同时使用templateUrl
和styleUrls
@Component({
selector: 'app-my-example',
templateUrl: './my-example.component.html',
styleUrls: ['./my-example.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyExampleComponent {}
Run Code Online (Sandbox Code Playgroud)
那么我缺少什么?我想确保如果我最终设置 CI 或类似的内容,我的测试不会中断。
或者我应该总是打电话compileComponents
?我的印象是,如果不需要的话,这样做不会那么有效。
那么,具体什么时候compileComponents
需要呢?
编辑:
这是我的笑话配置
module.exports = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/src/setupJest.ts'],
transformIgnorePatterns: …
Run Code Online (Sandbox Code Playgroud) 我真的很难尝试了解TestBed的工作原理以及如何使用它来模拟数据检索(通过AngularFire2即observables)/推进离线单元测试.如果有人可以提供一个简单的例子来查看它让事情变得如此简单.
下面是StateService的(部分).然后我将此服务注入另一个组件并打印出graphModules名称,例如
图的modules.component.html
<div *ngFor="let module of s.graphModules$ | async"><div class="module-card">{{module.name}}</div></div>
图的modules.component.ts
constructor(public s: StateService){}
state.service.ts
@Injectable()
export class StateService {
graphModules$: FirebaseListObservable<any>;
private auth;
constructor(public af: AngularFire) {
af.auth.subscribe(
latestAuth => {
this.graphModules$ = af.database.list('/graphModules', {
query: {
orderByChild: 'archived',
equalTo: false
}
});
},
errors => {
this.auth = {uid: 'AUTH PROBLEMS'};
throw 'Problems authenticating';
}
);
}
saveToDB(key: string, value: any) {
this.af.database.list('/graphModules').update(key, value);
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
我想要测试的是
1)给定"graphModules"的模拟/存根,将正确的.card模块数打印到DOM.
2)用s.saveToDB()更新其中一个模块后,在DOM中更新名称
另外,如果您对我的数据检索"架构"有其他意见,那么也是最受欢迎的:)
非常感谢!
编辑:
好的,我发现了如何修复1号.测试正确通过.问题2尚未得到解答.spec文件现在看起来像这样:
图的modules.component.spec.ts
class …
Run Code Online (Sandbox Code Playgroud) 当将以下配置用于测试治具时,我会抱怨找不到该标签。MockSelectionToolComponent
直接替换in AppModule
可以很好地工作,因此还必须做其他事情...
// Add the imported module to the imports array in beforeEach
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MockSelectionToolComponent],
imports: [
AppModule
]
}).overrideModule(AppModule, {
remove: {
declarations: [SelectionToolComponent]
}
}).compileComponents();
fixture = TestBed.createComponent(MappingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.initialiseMap();
});
Run Code Online (Sandbox Code Playgroud)
错误:模板解析错误:“ app-selection-tool”不是已知元素:
我正在为我的角度应用完成测试台.但是在业力 - 茉莉花测试中存在一个问题,它会引发错误
抛出[object ErrorEvent]
我更新了node_modules作为我在以下链接中找到的解决方案 如何在我的Karma/Jasmine测试中调试"[object ErrorEvent] thrown"错误?
但现在错误随机出现,有时候测试床没有任何故障,有时会出现错误触发.有任何建议可以永久避免它吗?
PS - 如果您需要更多资源,请在评论中告诉我.谢谢!
SomeComponent.spec.ts
import { RouterTestingModule } from '@angular/router/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { SomeComponent } from './some.component';
import { HttpLoaderFactory } from '../app.module';
import { AppRoutingModule } from '../app-routing.module';
import …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 TestBed 为 Angular 组件编写集成测试。有一些数据被注入到材质对话框的组件中,使用@inject(MAT_DIALOG_DATA)
. 我想测试两个案例。一种是没有提供数据时,另一种是提供一些数据时。但我想为所有情况(在beforeEach
方法中)以相同的方式配置测试模块。因此,对于没有注入数据的情况,我将模块配置如下:
TestBed.configureTestingModule({
declarations: [
PostNewComponent
].concat(EntryComponents1),
imports: [TestingModule],
providers: [
PostService,
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: { close: (dialogResult: any) => {}, updateSize: () => {} }}
]
});
Run Code Online (Sandbox Code Playgroud)
然后我有一个案例,我想测试通过的测试数据。所以我尝试了以下方法来覆盖提供者。
TestBed.overrideProvider(MAT_DIALOG_DATA, {useValue : {name: "passedName"}});
Run Code Online (Sandbox Code Playgroud)
但它不会覆盖提供者。我调试了这个问题,发现 overrideProvider 最终在 core.js 中调用以下方法
/**
* Read the `ngInjectableDef` for `type` in a way which is immune to accidentally reading inherited
* value.
*
* @param type A type which …
Run Code Online (Sandbox Code Playgroud) angular ×10
testbed ×10
jasmine ×2
unit-testing ×2
angular-i18n ×1
angular-test ×1
angular9 ×1
angularfire2 ×1
components ×1
firebase ×1
fixtures ×1
jestjs ×1
mocking ×1
overriding ×1
testing ×1