我在为应用程序中的确认模式编写单元测试时遇到一些问题。这是我想测试的一段代码:
confirmModal(prompt = 'Are you sure?', title = 'Confirm'): Observable<boolean> {
const modal = this.ngbModal.open(
ConfirmModalComponent, { backdrop: 'static' });
modal.componentInstance.prompt = prompt;
modal.componentInstance.title = title;
return from(modal.result).pipe(
catchError(error => {
console.warn(error);
return of(undefined);
})
);
}
有什么建议或例子吗?
我根据您的代码片段编写了以下测试类:
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ConfirmModalComponent } from './confirm-modal.component';
import { MyComponent } from './test';
// Mock class for NgbModalRef
export class MockNgbModalRef {
componentInstance = {
prompt: undefined,
title: undefined
};
result: Promise<any> = new Promise((resolve, reject) => resolve(true));
}
describe('MyComponent tests', () => {
let fixtureUnderTest: ComponentFixture<MyComponent>;
let componentUnderTest: MyComponent;
let ngbModal: NgbModal;
let mockModalRef: MockNgbModalRef = new MockNgbModalRef();
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [
NgbModule.forRoot()
]
}).compileComponents();
fixtureUnderTest = TestBed.createComponent(MyComponent);
componentUnderTest = fixtureUnderTest.componentInstance;
ngbModal = TestBed.get(NgbModal);
});
it('should open modal', () => {
spyOn(ngbModal, 'open').and.returnValue(mockModalRef);
componentUnderTest.confirmModal();
expect(ngbModal.open).toHaveBeenCalledWith(ConfirmModalComponent, { backdrop: 'static' });
});
it('should set prompt and title to defaults', () => {
spyOn(ngbModal, 'open').and.returnValue(mockModalRef);
componentUnderTest.confirmModal();
expect(mockModalRef.componentInstance.prompt).toBe('Are you sure?');
expect(mockModalRef.componentInstance.title).toBe('Confirm');
});
it('should return the result of the modal', (done: DoneFn) => {
spyOn(ngbModal, 'open').and.returnValue(mockModalRef);
componentUnderTest.confirmModal().subscribe((result: boolean) => {
expect(result).toBe(true);
done();
});
});
it('should return undefined if there is an error', (done: DoneFn) => {
spyOn(ngbModal, 'open').and.returnValue(mockModalRef);
// Override the result returned from the modal so we can test what happens when the modal is dismissed
mockModalRef.result = new Promise((resolve, reject) => reject(false));
componentUnderTest.confirmModal().subscribe((result: boolean) => {
expect(result).toBeUndefined();
done();
});
});
});
测试如下:
应该打开模式:测试ngbModal.open
使用正确的参数调用方法。
应该设置prompt
and title
为默认值:测试表明prompt
and title
模式打开后,属性将正确设置为其默认值。为此,我必须将以下对象添加到MockNgbModalRef
以便组件本身可以更新提示和标题的值。
componentInstance = {
prompt: undefined,
title: undefined
};
应该返回模态的结果:测试该值modal.result
从此方法返回。使用返回 Observable 的方法,我需要订阅它并在订阅中执行断言。我已经注射了DoneFn
以便done()
断言后被调用。这意味着如果断言从未发生(例如组件中存在错误),done()
永远不会被调用并且测试将失败。
如果出现错误,应返回未定义:与 #3 类似,但它会检查模式的结果是否被拒绝(即存在错误),然后返回未定义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)