Angular Jasmine单元测试mat-Autocomplete过滤器

huangapple go评论73阅读模式
英文:

Angular Jasmine unit test cases for mat-Autocomplete filter

问题

我正在尝试编写Angular单元测试用例,以通过插入输入数据来过滤mat-autocomplete选项,但我无法为值更改输入实现代码覆盖。

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { HttpClientTestingModule } from '@angular/common/http/testing';

import { AppComponent } from './app.component';

const mockData = [
  {
    "id": 1,
    "name": "One"
  },
  {
    "id": 2,
    "name": "Two"
  },
  {
    "id": 3,
    "name": "Three"
  }
];

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  const formBuilder: FormBuilder = new FormBuilder();

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        FormsModule,
        ReactiveFormsModule,
        MatAutocompleteModule,
        MatFormFieldModule,
        MatInputModule,
      ],
      declarations: [AppComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        { provide: FormBuilder, useValue: formBuilder },
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('getSysValuechanges.', () => {
    const spyFilter = spyOn<any>(component, 'getFilterData');
    component.form.controls.name.setValue('Rambo');
    expect(spyFilter).toHaveBeenCalled();
  });
});

请注意,你需要导入CUSTOM_ELEMENTS_SCHEMA,并确保在Angular的测试模块中使用它。这个测试用例的目的是测试getFilterData方法是否在form.controls.name的值更改时被调用。你可以使用spyOn来监视这个方法是否被调用。

英文:

I'm trying to write Angular unit test cases for filtering the mat-autocomplete options by inserting input data, but I couldn't able to do code coverage for value changes input.

app.component.html:

  &lt;div class=&quot;container&quot;&gt;
&lt;form [formGroup]=&quot;form&quot;&gt;
&lt;mat-form-field&gt;
&lt;input
matInput
type=&quot;text&quot;
formControlName=&quot;name&quot;
[matAutocomplete]=&quot;auto1&quot;
/&gt;
&lt;mat-autocomplete #auto1=&quot;matAutocomplete&quot;&gt;
&lt;mat-option *ngFor=&quot;let data of data | async&quot; [value]=&quot;data.name&quot;&gt;
{{ data.name }}
&lt;/mat-option&gt;
&lt;/mat-autocomplete&gt;
&lt;/mat-form-field&gt;
&lt;/form&gt;
&lt;/div&gt;

app.component.ts:

 import { Component, OnInit } from &#39;@angular/core&#39;;
import { FormBuilder, FormGroup } from &#39;@angular/forms&#39;;
import { map, Observable, startWith } from &#39;rxjs&#39;;
@Component({
selector: &#39;my-app&#39;,
templateUrl: &#39;./app.component.html&#39;,
styleUrls: [ &#39;./app.component.css&#39; ]
});
export class AppComponent implements OnInit {
data = [{
&quot;id&quot;: 1,
&quot;name&quot;: &quot;One&quot;
},{
&quot;id&quot;: 2,
&quot;name&quot;: &quot;Two&quot;
},{
&quot;id&quot;: 3,
&quot;name&quot;: &quot;Three&quot;
}];
form: FormGroup = this.formBuilder.group({
name: [&#39;&#39;],
});
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.filteredNames = this.form.controls[&#39;name&#39;].valueChanges.pipe(
startWith(&#39;&#39;),
map((value) =&gt; this.getFilterData(value))
);
}
getFilterData(value) {
const filterValue = value.toLowerCase();
return this.data.filter((val) =&gt; val.name.toLowerCase().includes(filterValue));
}
}

app.component.spec.ts:

		import { HttpClientTestingModule } from &#39;@angular/common/http/testing&#39;;
import { CUSTOM_ELEMENTS_SCHEMA } from &#39;@angular/core&#39;;
import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;
import { FormBuilder, FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;
import { MatAutocompleteModule } from &#39;@angular/material/autocomplete&#39;;
import { MatFormFieldModule } from &#39;@angular/material/form-field&#39;;
import { MatInputModule } from &#39;@angular/material/input&#39;;
import { AppComponent } from &#39;./app.component&#39;;
const mockData = [{
&quot;id&quot;: 1,
&quot;name&quot;: &quot;One&quot;
},{
&quot;id&quot;: 2,
&quot;name&quot;: &quot;Two&quot;
},{
&quot;id&quot;: 1,
&quot;name&quot;: &quot;Three&quot;
}];
describe(&#39;AppComponent&#39;, () =&gt; {
let component: AppComponent;
let fixture: ComponentFixture&lt;AppComponent&gt;;
const formBuilder: FormBuilder = new FormBuilder();
beforeEach(async () =&gt; {
await TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
FormsModule,
ReactiveFormsModule,
MatAutocompleteModule,
MatFormFieldModule,
MatInputModule,
],
declarations: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [
{ provide: FormBuilder, useValue: formBuilder },
],
}).compileComponents();
});
beforeEach(() =&gt; {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it(&#39;should create&#39;, () =&gt; {
expect(component).toBeTruthy();
});
it(&#39;getSysValuechanges.&#39;, () =&gt; {
const spyFilter = spyOn&lt;any&gt;(component, &#39;getFilterData&#39;);
component.form.controls.name.setValue(&#39;Rambo&#39;);
expect(spyFilter).toHaveBeenCalled();
});
});

Can anyone please help me to write test cases for valuechanges on mat-autocomplete input element.

答案1

得分: 0

我找到了,忘了创建模拟服务并注入到规范中。

let serviceSpy: jasmine.SpyObj<AppService>;
serviceSpy.getData.and.returnValue(of(mockData as any));

并注入模拟服务。

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [,,,,]
    declarations: [AppComponent],
    providers: [
      { provide: AppService, useValue: serviceSpy},
    ],
  }).compileComponents();
});
英文:

I found it, forgot to create mock service & inject in to spec.

      let serviceSpy: jasmine.SpyObj&lt;AppService&gt;;
serviceSpy.getData.and.returnValue(of(mockData as any));

and inject the mock service.

       beforeEach(async () =&gt; {
await TestBed.configureTestingModule({
imports: [,,,,]
declarations: [AppComponent],
providers: [
{ provide: AppService, useValue: serviceSpy},
],
}).compileComponents();
});

huangapple
  • 本文由 发表于 2023年2月24日 17:31:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定