模拟 Angular 服务类属性或变量

Ani*_*Das 4 angular angular-unit-test angular-test

我正在对一个 Angular 应用程序进行单元测试,我需要模拟一个服务。我可以毫无问题地模拟服务方法,但是当我尝试以相同的方式模拟属性时,它给了我错误

我的配置服务有一个属性和一种方法,我想模​​拟该属性,因为我无法生成该值。

服务

@Injectable()
export class ConfigService {
  public config = 'iamdirect';

  constructor(private http: Http) {
   }

  public load(): Observable<any> {
    return 'Iamokey';
  }
}
Run Code Online (Sandbox Code Playgroud)

在角度测试中模拟服务

// mocking config service
configService = TestBed.get(ConfigService);
spyOn(configService, 'load')
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: 'testemail@email.com'
  }
}));
Run Code Online (Sandbox Code Playgroud)

当我这样做时,它给了我错误。

spyOn(configService, 'config') //config is the property
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: 'testemail@email.com'
  }
}));
Run Code Online (Sandbox Code Playgroud)

Anu*_*ara 5

您可以使用 jasmine 创建间谍对象,也可以使用模拟对象作为服务存根。

let mockConfigService;
let configService: ConfigService;
const subject = new Subject();

beforeEach(() => {

  mockConfigService = {
      config: 'test text',
      load: () => subject.asObservable()
  }

  TestBed.configureTestingModule({
   providers: [
      {provide: ConfigService, useValue: mockConfigService},
   ]
  });

  configService = TestBed.get(ConfigService);
});
Run Code Online (Sandbox Code Playgroud)

  • 您可以仅覆盖您需要的属性并使用以下方法保留服务: class MockConfigService extends ConfigService { ..} (2认同)