茉莉花服务函数不返回模拟值
jasmine serivce function not returning mock value
我是第一次进行 angular 测试,从早上开始我就在努力测试它。我在 TestBed 中添加了两个模块并进行了注入,但始终调用真正的方法而不是从 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。您必须先注入 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();
});
我也像其他答案中提到的那样将依赖服务的注入移动到 beforeEach 块中,以便它也可以应用于其他测试
我是第一次进行 angular 测试,从早上开始我就在努力测试它。我在 TestBed 中添加了两个模块并进行了注入,但始终调用真正的方法而不是从 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。您必须先注入 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();
});
我也像其他答案中提到的那样将依赖服务的注入移动到 beforeEach 块中,以便它也可以应用于其他测试