我正在尝试测试自动完成的输入,我希望刷新列表的方法在1秒钟后被调用。因此,我使用debounceTime创建了一个Subject,对于输入中的每个keyup事件,我都会使用输入的值调用.next函数。 在测试中,我只想检查在更改输入值1秒后是否调用了refresh方法。我在刷新方法上创建了一个间谍,并希望使用输入的值来调用它,但由于显示了方法中的console.log且测试失败,因此间谍似乎无法正常工作:
●控制台
console.log src/app/components/my-component/my-component.component.ts:28
call to a service
●MyComponent›应该在值更改后刷新2秒
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
["P"]
But it was not called.
我试图直接使用组件变量创建间谍,但是它不起作用。
my-component.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
form : FormGroup;
subTermField: Subject<String> = new Subject<String>();
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
term: ['']
})
this.subTermField.pipe(debounceTime(1000)).subscribe(this.refreshData)
}
refreshData(value) {
console.log('call to a service');
}
}
my-component.component.html
<form [formGroup]="form">
<input formControlName="term" type="text" id="input-term" (keyup)="subTermField.next($event.target.value)"/>
</form>
my-component.component.spec.ts
import { async, ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';
import { MyComponent } from './my-component.component';
import { By } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports: [FormsModule, ReactiveFormsModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should handle refreshing 2 secondes after the value change', fakeAsync(() => {
let f = jest.spyOn(MyComponent.prototype,'refreshData');
fixture.detectChanges();
const input = fixture.debugElement.query(By.css('#input-term')).nativeElement;
input.value = "P";
input.dispatchEvent(new Event('keyup'));
tick(1000)
expect(f).toHaveBeenCalledWith("P");
}));
});
在测试中,我希望使用“ P”调用间谍,而不调用原始方法。