无法为 NgForm 对象创建间谍:找不到要监视的对象
Unable to create spy for NgForm object: could not find an object to spy upon for
我在为 NgForm
对象创建间谍时遇到问题。我正在使用 Angular11 组件。
我的测试基本上是这样的(略):
let component: AuthComponent;
let fixture: ComponentFixture<AuthComponent>;
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting());
....
fixture = TestBed.createComponent(AuthComponent);
....
}
和
describe('onSubmit', () => {
it('makes expected calls', () => {
const ngFormStub: NgForm = <NgForm>{};
spyOn(ngFormStub, 'resetForm').and.callThrough();
component.onSubmit(ngFormStub);
expect(ngFormStub.resetForm).toHaveBeenCalled();
});
});
我是否需要以某种方式从夹具中获取 ngFormStub
的值?我试过了,但没用:
const ngFormStub: NgForm = component.form; // this didn't work
但是,我的测试显示这个错误:
Error: <spyOn> : could not find an object to spy upon for resetForm()
注意:在我的组件上,onSubmit()
方法以对 form.resetForm()
的调用结束,这正是我要测试的内容。
这是我的项目测试配置:
"jasmine": "^3.6.3",
"jasmine-core": "^3.6.0",
"jasmine-spec-reporter": "^6.0.0",
"karma": "^5.2.3",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "^4.0.1",
"karma-jasmine-html-reporter": "^1.5.4",
原来我需要像这样伪造方法引用:
....
fixture.detectChanges();
const ngFormStub: NgForm = <NgForm>{
resetForm: () => null,
value: {
email: "test@test.com",
password: "password"
},
valid: true
};
....
此外,我需要这个:
TestBed.configureTestingModule({
declarations: [AuthComponent],
imports: [FormsModule, ReactiveFormsModule],
....
我在为 NgForm
对象创建间谍时遇到问题。我正在使用 Angular11 组件。
我的测试基本上是这样的(略):
let component: AuthComponent;
let fixture: ComponentFixture<AuthComponent>;
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting());
....
fixture = TestBed.createComponent(AuthComponent);
....
}
和
describe('onSubmit', () => {
it('makes expected calls', () => {
const ngFormStub: NgForm = <NgForm>{};
spyOn(ngFormStub, 'resetForm').and.callThrough();
component.onSubmit(ngFormStub);
expect(ngFormStub.resetForm).toHaveBeenCalled();
});
});
我是否需要以某种方式从夹具中获取 ngFormStub
的值?我试过了,但没用:
const ngFormStub: NgForm = component.form; // this didn't work
但是,我的测试显示这个错误:
Error: <spyOn> : could not find an object to spy upon for resetForm()
注意:在我的组件上,onSubmit()
方法以对 form.resetForm()
的调用结束,这正是我要测试的内容。
这是我的项目测试配置:
"jasmine": "^3.6.3",
"jasmine-core": "^3.6.0",
"jasmine-spec-reporter": "^6.0.0",
"karma": "^5.2.3",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "^4.0.1",
"karma-jasmine-html-reporter": "^1.5.4",
原来我需要像这样伪造方法引用:
....
fixture.detectChanges();
const ngFormStub: NgForm = <NgForm>{
resetForm: () => null,
value: {
email: "test@test.com",
password: "password"
},
valid: true
};
....
此外,我需要这个:
TestBed.configureTestingModule({
declarations: [AuthComponent],
imports: [FormsModule, ReactiveFormsModule],
....