【问题标题】:Jasmine Mocking Provider with Method and Properties Angluar 9具有方法和属性 Angular 9 的 Jasmine 模拟提供程序
【发布时间】:2020-09-28 17:39:55
【问题描述】:

我正在尝试模拟 angularx-social-login npm 包。我想要的是默认应该创建测试以通过。在我的测试规范中,我有:

  let component: Component;
  let fixture: ComponentFixture<Component>;
  let spy;

  beforeEach(async(() => {
    spy = jasmine.createSpyObj('SocialAuthService', ['signIn', 'signOut'], ['authState']);
    TestBed.configureTestingModule({
      declarations: [
        Component
      ],
      providers: [
        { provide: SocialAuthService, useValue: spy }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

使用此代码,我得到错误无法读取未定义的属性订阅。这是预期的,因为我没有设置 authState 的订阅,因为在我的组件中我有这个:

this.socialAuthService.authState;

以上返回 observable。但是,当我在每个之前的第一行添加这行代码时:

spy.authState.and.returnValue(of());

它说无法读取属性和未定义的。在网上做了一些研究后,我可以看到很多建议是使用 spyOnProperty,但是当我使用 spyOnProperty(spy, 'authState', 'get'); 之类的东西时,我收到错误 Failed: : authState is not declared 可配置的。我不确定如何处理这个问题,任何帮助将不胜感激。

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

    我认为您错误地使用了jasmine.createSpyObj。它只需要 2 个参数,而不是 3 个。

    第一个参数是间谍的字符串名称,第二个参数是您要模拟的公共方法数组。看到你有this.socialAuthService.getAuthState(),你需要在第二个参数中添加getAuthState

    试试这个:

     let component: Component;
      let fixture: ComponentFixture<Component>;
      let spy;
    
      beforeEach(async(() => {
        // add all other public properties required into the second argument inside of the array ** in this case remove it since you don't need it
        spy = jasmine.createSpyObj('SocialAuthService', []);
        TestBed.configureTestingModule({
          declarations: [
            Component
          ],
          providers: [
            { provide: SocialAuthService, useValue: spy }
          ]
        })
          .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(HeaderComponent);
        component = fixture.componentInstance;
        // I am not sure when you require the value but let's assume you need it in the ngOnInit
       // so we have to put it here
        // spy.getAuthState.and.returnValue(of(null)); // now we are mocking the return value of getAuthState, ** comment out this line, you don't need it
        spy.authState = of(null); // ** mock it to what you would like here
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    

    【讨论】:

    • 对不起,我写错了,我的意思是我需要测试 this.SocialAuthService.authState ,它是一个属性而不是一个方法。
    • 啊,我明白了 spy.authState = of(null) 完美运行。
    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多