Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing jasmine serivce函数不返回模拟值_Unit Testing_Jasmine_Karma Jasmine - Fatal编程技术网

Unit testing jasmine serivce函数不返回模拟值

Unit testing jasmine serivce函数不返回模拟值,unit-testing,jasmine,karma-jasmine,Unit Testing,Jasmine,Karma Jasmine,我第一次从事角度测试,从monring开始,我一直在努力测试。我在TestBed和injected中添加了这两个模块,但始终调用real方法,而不是从getMockFeatureState()返回值。请帮忙解决这个问题。坦克斯 beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientModule ], providers: [ FeatureToggleServic

我第一次从事角度测试,从monring开始,我一直在努力测试。我在TestBed和injected中添加了这两个模块,但始终调用real方法,而不是从
getMockFeatureState()
返回值。请帮忙解决这个问题。坦克斯

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientModule ],
      providers: [ FeatureToggleService, ConfigService]
    });
  });

  it('should return values based on mock feature state', () => {
    const featureService = TestBed.inject(FeatureToggleService);
    const configService = TestBed.inject(ConfigService);
    const mockFeaturesSpy = spyOn(configService, 'getMockFeatures')
        .and.returnValue(getMockFeatureState());
    expect(featureService.isFeatureEnabled('feature1')).toBeFalsy();
    expect(featureService.isFeatureEnabled('feature2')).toBeFalsy();
  });

我最近在一次测试中遇到了同样的问题。问题在于
TestBed.inject
的顺序。如果FeatureToggleService需要配置服务。您必须首先注入ConfigService并在注入featureService之前模拟它。你可以试试

  it('should return values based on mock feature state', () => {
    const configService = TestBed.inject(ConfigService);
    const mockFeaturesSpy = spyOn(configService, 'getMockFeatures')
        .and.returnValue(getMockFeatureState());
    const featureService = TestBed.inject(FeatureToggleService);
    expect(featureService.isFeatureEnabled('feature1')).toBeFalsy();
    expect(featureService.isFeatureEnabled('feature2')).toBeFalsy();
  });

我还将依赖项服务的注入移动到beforeach块中,如其他答案中所述,以便它也可以应用于其他测试。非常感谢。