这次我试图模拟一个服务(做http调用)来测试一个组件.
@Component({
selector: 'ub-funding-plan',
templateUrl: './funding-plan.component.html',
styleUrls: ['./funding-plan.component.css'],
providers: [FundingPlanService]
})
export class FundingPlanComponent implements OnInit {
constructor(private fundingPlanService: FundingPlanService) {
}
ngOnInit() {
this.reloadFundingPlans();
}
reloadFundingPlans() {
this.fundingPlanService.getFundingPlans().subscribe((fundingPlans: FundingPlan[]) => {
this.fundingPlans = fundingPlans;
}, (error) => {
console.log(error);
});
}
}
Run Code Online (Sandbox Code Playgroud)
该文件(2.0.0版本)解释说,你应该嘲笑的服务.使用相同的TestBed配置:
describe('Component: FundingPlan', () => {
class FundingPlanServiceMock {
getFundingPlans(): Observable<FundingPlan> { return Observable.of(testFundingPlans) }
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [FundingPlanComponent],
providers: [
{ provide: FundingPlanService, useClass: FundingPlanServiceMock },
]
});
fixture …Run Code Online (Sandbox Code Playgroud) 我有一个角度为2的组件,它响应路由参数的变化(组件不会从头开始重新加载,因为我们没有移出主路径.这是组件代码:
export class MyComponent{
ngOnInit() {
this._routeInfo.params.forEach((params: Params) => {
if (params['area']){
this._pageToShow =params['area'];
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种享受,并_pageToShow适合导航.
我正在尝试测试路线变化的行为(所以这是可观察的第二个触发器,但它拒绝为我工作.)这是我的尝试:
it('sets PageToShow to new area if params.area is changed', fakeAsync(() => {
let routes : Params[] = [{ 'area': "Terry" }];
TestBed.overrideComponent(MyComponent, {
set: {
providers: [{ provide: ActivatedRoute,
useValue: { 'params': Observable.from(routes)}}]
}
});
let fixture = TestBed.createComponent(MyComponent);
let comp = fixture.componentInstance;
let route: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
comp.ngOnInit();
expect(comp.PageToShow).toBe("Terry");
routes.splice(2,0,{ 'area': "Billy" });
fixture.detectChanges();
expect(comp.PageToShow).toBe("Billy");
}));
Run Code Online (Sandbox Code Playgroud)
但是 …
jasmine angular2-routing angular2-testing angular2-observables angular
我正在为我的angular2组件创建单元测试用例.
到目前为止测试用例正确运行.
但我面临着有关异步调用的问题.
对于前者 我有以下创建新用户的方法,如果用户已经存在则会抛出错误:
onSubmit():Observable<any> {
this._userService.saveUser(this.user).subscribe(
(response) => {
this._directoryService.getDirectoryById(this.selectedDirectory._id).subscribe(
(directory) => {
this.users = directory[0].users;
},
(error) => {
return error;
}
);
},
(error) => {
return error;
}
);
return ;
}
Run Code Online (Sandbox Code Playgroud)
在我的服务中,我使用以下内容抛出错误:
if (alreadyExist) {
let error = "user already exist in database";
return Observable.throw(error);
}
Run Code Online (Sandbox Code Playgroud)
现在我期待这个方法抛出一个错误:
expect( function(){ app.onSubmit(); } )
.toThrow(new Error("User already exist in database"));
Run Code Online (Sandbox Code Playgroud)
根据我的理解,这个测试用例应该是成功的,但是在我的测试用例失败后我得到了以下错误:
抛出异常的预期函数.
我尝试了多个expect块:
expect(app.onSubmit()).toThrowError(new Error("User already exist in database"));
Run Code Online (Sandbox Code Playgroud)
但仍然没有取得任何成功.
任何输入?
谢谢
当我运行这个单元测试时:
it('can click profile link in template', () => {
const landingPageLinkDe = linkDes[0];
const profileLinkDe = linkDes[1];
const aboutLinkDe = linkDes[2];
const findLinkDe = linkDes[3];
const addLinkDe = linkDes[4];
const registerLinkDe = linkDes[5];
const landingPageLinkFull = links[0];
const profileLinkFull = links[1];
const aboutLinkFull = links[2];
const findLinkFull = links[3];
const addLinkFull = links[4];
const registerLinkFull = links[5];
navFixture.detectChanges();
expect(profileLinkFull.navigatedTo)
.toBeNull('link should not have navigated yet');
profileLinkDe.triggerEventHandler('click', { button: 0 });
landingPageLinkDe.triggerEventHandler('click', { button: 0 });
aboutLinkDe.triggerEventHandler('click', { button: 0 …Run Code Online (Sandbox Code Playgroud) 因此,在Angular2的RC5版本中,他们弃用HTTP_PROVIDERS并引入了HttpModule.对于我的应用程序代码,这工作正常,但我正在努力在我的Jasmine测试中进行更改.
这是我目前在我的规范中所做的事情,但由于不推荐使用HTTP_PROVIDERS,我现在应该做些什么呢?有什么我需要提供而不是HTTP_PROVIDERS?在RC5世界中这样做的正确方法是什么?
beforeEach(() => {
reflectiveInjector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS,
...
]);
//other code here...
});
it("should....", () => { ... });
Run Code Online (Sandbox Code Playgroud) 我正在使用angular2进行组件测试.在我的html模板中,我使用翻译管道.这是测试的代码:
import { ComponentFixture, TestBed ,getTestBed} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RightComponent } from './right.component';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {Injector} from "@angular/core";
let comp: RightComponent;
let fixture: ComponentFixture<RightComponent>;
let el: DebugElement;
let translate: TranslateService;
let injector: Injector;
describe('testComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ RightComponent ]
});
injector = getTestBed();
translate = injector.get(TranslateService);
fixture = TestBed.createComponent(RightComponent);
comp = fixture.componentInstance; // BannerComponent test instance
// get …Run Code Online (Sandbox Code Playgroud) 我们的项目结构如下:Angular2-webpack-starter.
我们的项目成功编译,构建并可在浏览器中看到.这里没问题.
但是当我们尝试运行测试用例时,karma and jasmine我们会收到此错误.
XXXXComponent
:heavy_multiplication_x: Should Match Current Tab as 1
Chrome 55.0.2883 (Mac OS X 10.10.5)
Error: Unexpected value 'FormGroup' declared by the module 'DynamicTestModule'
at SyntaxError.ZoneAwareError (webpack:///~/zone.js/dist/zone.js:811:0 <- config/spec-bundle.js:74048:33)
at SyntaxError.BaseError [as constructor] (webpack:///~/@angular/compiler/src/facade/errors.js:26:0 <- config/spec-bundle.js:78913:16)
at new SyntaxError (webpack:///~/@angular/compiler/src/util.js:151:0 <- config/spec-bundle.js:6408:16)
at webpack:///~/@angular/compiler/src/metadata_resolver.js:475:0 <- config/spec-bundle.js:19829:40
at Array.forEach (native)
at CompileMetadataResolver.getNgModuleMetadata (webpack:///~/@angular/compiler/src/metadata_resolver.js:457:0 <- config/spec-bundle.js:19811:54)
at JitCompiler._loadModules (webpack:///~/@angular/compiler/src/jit/compiler.js:165:25 <- config/spec-bundle.js:55462:64)
at JitCompiler._compileModuleAndAllComponents (webpack:///~/@angular/compiler/src/jit/compiler.js:144:25 <- config/spec-bundle.js:55441:52)
at JitCompiler.compileModuleAndAllComponentsSync (webpack:///~/@angular/compiler/src/jit/compiler.js:98:0 <- config/spec-bundle.js:55395:21)
at TestingCompilerImpl.compileModuleAndAllComponentsSync (webpack:///~/@angular/compiler/bundles/compiler-testing.umd.js:482:0 …Run Code Online (Sandbox Code Playgroud) javascript typescript karma-jasmine angular2-testing angular
任何人都可以帮我在Angular 2中测试Http请求.我有一个服务从两个http请求获取流.我如何在测试中模拟这种行为?
loadData() {
return Observable.forkJoin(
this.http.get('file1.json').map((res:Response) => res.json()),
this.http.get('file2.json').map((res:Response) => res.json())
).map(data => {
return {
x: data[0],
y: data[1]
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试代码,我试图使用一个连接数组,但我收到一条错误消息"失败:连接已经解决".我已将连接体留空,以避免暴露敏感数据.
describe('Test Load Init Data', () => {
it('should load Menu Zones and Menu Sections',
inject([XHRBackend, AppInitService], (mockBackend, appInitService) => {
console.log('Lets do some testing');
//first we register a mock response
mockBackend.connections.subscribe(
(connection:MockConnection) => {
return [
connection.mockRespond(new Response(
new ResponseOptions({
body: []
})
)),
connection.mockRespond(new Response(
new ResponseOptions({
body: []
})
))
];
});
appInitService.loadData().subscribe(data …Run Code Online (Sandbox Code Playgroud) 我需要能够模拟激活的路由参数才能测试我的组件.
到目前为止,这是我最好的尝试,但它不起作用.
{ provide: ActivatedRoute, useValue: { params: [ { 'id': 1 } ] } },
Run Code Online (Sandbox Code Playgroud)
ActivatedRoute在实际组件中使用如下:
this.route.params.subscribe(params => {
this.stateId = +params['id'];
this.stateService.getState(this.stateId).then(state => {
this.state = state;
});
});
Run Code Online (Sandbox Code Playgroud)
我目前尝试的错误很简单:
TypeError: undefined is not a constructor (evaluating 'this.route.params.subscribe')
任何帮助将不胜感激.
我正在测试一个Angular2组件,并且想要断言组件的nativeElement属性,但是没有打字稿定义.我的测试看起来像这样:
beforeEach( () => {
myComponentFixture = TestBed.createComponent(MyComponent);
myComponent = myComponentFixture.componentInstance;
});
it('Should display something', fakeAsync(() => {
myComponentFixture.detectChanges();
expect(myComponentFixture.nativeElement.textContent).toContain('something');
}));
Run Code Online (Sandbox Code Playgroud)
问题是,在我输入后nativeElement.没有IntelliSense,因为我认为没有nativeElement的类型.我可能想要检查更多属性,如innerHtml,id等.这个示例测试可能没有意义,但我可以测试一些特定的DOM元素的属性使用myComponentFixture.debugElement.query(By.css('#myElement')).nativeElement
angular ×10
angular2-testing ×10
jasmine ×2
javascript ×2
typescript ×2
angular-cli ×1
angularjs ×1
mocking ×1
service ×1