如何使用Angular TestBed作为提供者传递Jasmine间谍对象

问题描述

我希望使用Angular的(版本7)TestBed来测试组件,并查看注入的服务是否具有称为的方法。

他在观看this tutorial时,大约23:18展示了如何创建茉莉花的天空,因此您可以使用诸如toHaveBeenCalledTimes这样的测试方法

除了使用TestBed创建组件而不是像视频中那样手动实例化之外,我正在尝试做同样的事情。

我有以下内容。

describe('AppComponent',() => {
    beforeEach(async(() => {
        
        fakeStartupService = jasmine.createSpyObj(fakeStartupService,['start']);
        //fakeStartupService.start.and.returnValue(null);
                        
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule,],providers: [
                ErrorHandler,{ provide: StartupService,useValue: fakeStartupService },declarations: [
                AppComponent,}).compileComponents();     
    }));
    
    it('should have called start services start'),() => {
        expect(fakeStartupService.start).toHaveBeenCalledTimes(100);
    } 
});

第一个问题是,当我键入expect(fakeStartupService.时,我没有像视频中那样显示start方法的代码完成。

另一个(主要)问题是,尽管上面的代码可以编译并运行,但我不认为它是正确的,因为expect(fakeStartupService.start).toHaveBeenCalledTimes(100);不会不会失败-组件仅调用它一次,但是我断言100次,所以它应该失败。

我猜想在useValue中使用{ provide: StartupService,,所以也许这是不正确的

我想知道

  • 正在使用这样的间谍,如果可以的话,我该怎么做?

预先感谢

[UPDATE1]

实际上我有语法错误(描述后加括号)。

以下内容似乎对我有用。

it('should have called start services start once',async () => {
  const fixture = TestBed.createComponent(AppComponent);    
  const app = fixture.debugElement.componentInstance;

  // As ngOnInit is async,use detectChanges and whenStable to wait for it to be finished.
  fixture.detectChanges();
  await fixture.whenStable()      
  expect(fakeStartupService.start).toHaveBeenCalledTimes(1);    
});

另外,为了等待我ngOnInit异步,我添加了

 fixture.detectChanges();
 await fixture.whenStable()     

现在,唯一的小问题是他们如何在视频中获得智能感知。

解决方法

我观看了一部分视频,不是智能感知/自动完成。好的,从某种程度上讲,它来自Visual Studio Code,而IDE则将您键入的内容与文档中先前键入的内容进行匹配(并尽力而为)。我希望这是有道理的。

要在这种情况下获得真正的智能感知和自动完成功能,请在您的项目中的某个位置创建一个名为spied.ts的接口,其定义如下:

export type Spied<T> = {
  [Method in keyof T]: jasmine.Spy;
};

然后,当您定义fakeStartupService时,请按照以下步骤进行操作:

import { Spied } from './where/spied/type/file/was/saved';
....
let fakeStartupService: Spied<StartupService>;

现在,当您键入fakeStarupService.st时,应该会出现start的自动完成/智能提示。

我使用了这个,我从这篇文章中得到了这个:https://pragmatic-coder.net/typesafe-jasmine-spies/。向下滚动到The fix

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...