首页 > 解决方案 > 无法读取未定义的属性“returnValue”

问题描述

我正在根据官方 Angular文档编写我的第一个单元测试

但是,当我尝试使用他们的示例时,我在尝试测试时遇到了上述错误。我环顾四周,但找不到有关此特定错误的任何信息。

我的尝试:

import { TestBed } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';

import { VService } from './vservice';

fdescribe('VService', () => {
 let VServiceSpy: jasmine.SpyObj<VService>;

 beforeEach(() => {
   const spy = jasmine.createSpyObj('VService', ['getAll']);

   TestBed.configureTestingModule({
     // this fixed an issue which is why i added it
     providers: [{ provide: HttpClient, useValue: spy }]
   });

   VServiceSpy = TestBed.get(VService);
 });

 it('should be created', () => {
   expect(VServiceSpy).toBeTruthy();
 });

 it('#getAll should return stubbed value from a spy', () => {
   const stubValue = [
     {
       id: '1',
       name: 'Repairs',
       number: '000000001',
       address: '1 Test Rd. Tampa, OH 44442',
       phoneNumber: '111-111-1111',
       emailAddress: 'test@email.com'
     }
   ];
   // here is the issue
   VServiceSpy.getAll.and.returnValue(stubValue);

   expect(VServiceSpy.getAll()).toBe(stubValue, 'service returned stub value');
   expect(VServiceSpy.getAll.calls.count())
     .toBe(1, 'spy method was called once');
   expect(VServiceSpy.getAll.calls.mostRecent().returnValue)
     .toBe(stubValue);
 });
});

我认为这是我的服务返回可观察的问题吗?不过,我认为这很标准。我的服务没有什么特别之处。

标签: angularunit-testing

解决方案


你很亲密。要测试服务,您需要将该服务添加到 providers 数组。所以改变这个:

TestBed.configureTestingModule({
  // this fixed an issue which is why i added it
  providers: [{ provide: HttpClient, useValue: spy }]
});

像这样:

TestBed.configureTestingModule({
  providers: [
    VService,
    { provide: HttpClient, useValue: spy }
  ]
});

注意:您可以在设置 HttpClient 时对其进行间谍活动,但也可以查看此处HttpClientTestingModule详细记录的内容。


推荐阅读