【问题标题】:How to pass a Jasmine spy object as a provider using Angular TestBed如何使用 Angular TestBed 将 Jasmine 间谍对象作为提供者传递
【发布时间】:2020-08-16 08:27:48
【问题描述】:

我希望使用 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); 确实 not 失败 - 组件只调用它一次,但我断言 100 次,所以它应该失败。

我猜测在{ provide: StartupService, useValue: fakeStartupService }, 中使用useValue,所以这可能是不正确的

我想知道:是否可以使用这样的间谍,如果可以,我该怎么做?

更新

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

以下似乎对我有用。

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()     

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

【问题讨论】:

    标签: angular jasmine karma-jasmine angular-test


    【解决方案1】:

    我观看了视频的一部分,不是智能感知/自动完成。嗯,在某种程度上,它来自 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。

    【讨论】:

    • 我明白了,他们只需键入足够的次数,IDE 就可以“猜测”该属性。上面的Spied 类型完美,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2018-08-10
    • 2021-11-06
    • 2015-01-09
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多