在Angular 10中,可以使用Karma和Jasmine的spied方法来模拟和监视函数的行为。以下是一个示例解决方法,包含代码示例:
npm install karma jasmine karma-jasmine karma-chrome-launcher --save-dev
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
browsers: ['Chrome'],
files: [
// 添加你的测试文件路径
]
});
};
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ExampleComponent } from './example.component';
describe('ExampleComponent', () => {
let component: ExampleComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ExampleComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should call a function', () => {
spyOn(component, 'exampleFunction').and.callThrough();
component.exampleFunction();
expect(component.exampleFunction).toHaveBeenCalled();
});
});
exampleFunction() {
// 在此处编写你的代码
}
在测试文件中,使用spyOn
函数来监视exampleFunction
函数的调用,并使用callThrough
方法来实际调用原始函数。然后,可以使用toHaveBeenCalled
来断言函数是否被调用。
请注意,在运行测试之前,确保启动了Chrome浏览器。在项目的根目录中,运行以下命令:
ng test
这将运行Karma测试,并在控制台中显示测试结果。