茉莉花单元测试:无法在自定义 angular 下拉组件中触发更改事件

jasmine unit-testing: Can't trigger change event in custom angular dropdown component

我正在使用 jasmine 和 karma angular 组件进行单元测试。在模板组件中使用了自定义下拉组件:

   <div class="my-modal-body">
        <form [formGroup]="form" class="form-horizontal">
            <div class="padding-dropdown">
                <my-form-wrapper
                    label="Dateiformat"
                    labelClass="col-lg-4 two-col-label-size"
                    inputClass="col-lg-8 two-col-input-size"
                >
                    <my-dropdown
                        [items]="exportOptionen"
                        formControlName="dateiTyp"
                        (selectedChange)="exportFileChange($event)"
                    >
                    </my-dropdown>
                </my-form-wrapper>
            </div>

在我的测试中,我尝试测试值更改,但无法使其正常工作。但是我尝试设置该值,不会触发 exportFileChange。 而且我知道该组件是正确的,因为它已经投入生产。所以一定是测试出错了。

这是我的测试:

    it('dateiTyp auswahl excel', waitForAsync(() => {
        spyOn(component, 'exportFileChange');
        dateiTyp.setValue('Excel');
        component.dateiTyp.setValue('Excel', { emitEvent: true });
        fixture.detectChanges();
        fixture.whenStable().then(
            () => {
                expect(component.exportFileChange).toHaveBeenCalled();
                let exDiv = fixture.debugElement.query(By.css("#excelExportDiv"));
                expect(exDiv).not.toBeNull();
            }
        );
    }));

更改选择时,应调用 exportFileChange(event) 方法,并在模板中出现 div。组件中的 exportFileChange-Method 只是更改了一个布尔值。 我测试了更改测试中的布尔值并且有效,但事件仍然没有被触发。

以下是设置中最相关的部分:

describe('ExportModalComponent', () => {
   [...]
   let dateiTyp: jasmine.SpyObj<FormControl>;
   let dateiTypChange: Subject<string>;
[...]

beforeEach( waitForAsync(() => {
[...]
  dateiTyp = jasmine.createSpyObj('dateiTyp', ['value', 'setValue']);
  formGroup.get.withArgs('dateiTyp').and.returnValue(dateiTyp);
  dateiTypChange = new Subject();
  Object.defineProperty(dateiTyp, 'valueChanges', { value: dateiTypChange });
[...]

和我的-dropdown.component.d.ts:

export declare class myDropdownComponent implements ControlValueAccessor, OnInit, OnChanges 
{ [...] }

我可以更改 ExportModal 模板或 ExportModal 组件,但无法更改 myDropdownComponent 的实现或使用。

感谢您的每一次帮助!

谢谢!

这不是一个完整的答案,但应该对您有所帮助。

This 是一本好书。在这种情况下,我只是在 DebugElement.

上使用 triggerEventHandler

像这样:

it('should do abc', () => {
   // get a handle on the debugElement
   const myDropDown = fixture.debugElement.query(By.css('my-dropdown'));
   // the first argument is the name of the event you would like to trigger
   // and the 2nd argument of type object (or anything) is the $event you want to mock for the calling function
   myDropDown.triggerEventHandler('selectedChange', { /* mock $event here */});
   // continue with tests
});

我不完全确定您的组件是如何连接的,但这是我发现为自定义组件引发自定义事件的最佳方式。