gpt4 book ai didi

angular - 引用错误 : Cannot access Service' before initialization

转载 作者:行者123 更新时间:2023-12-04 11:48:48 25 4
gpt4 key购买 nike

当我在 angular8 应用程序上使用 jasmine 运行单元测试时出现错误。
我有一个服务,在这个服务中我正在注入(inject)另一个服务

@Injectable({
providedIn: 'root'
})

export class FirstService {
constructor(private http: HttpClient, private configService: ConfigurationService) { }

当我执行 npm run test 时,总是出现错误:

An error was thrown in afterAll ReferenceError: Cannot access 'ConfigurationService' before initialization at Module.ConfigurationService (http://localhost:9876/_karma_webpack_/main.js:1095:112)



有什么帮助吗?

最佳答案

您需要提供 ConfigService 的模拟。因为它是 FirstService 的依赖项.最简单的方法是使用 spy 。

就像是:

let firstService: FirstServicec;
let configServiceSpy: jasmine.SpyObj<ConfigService>;

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

TestBed.configureTestingModule({
providers: [
FirstService,
{ provide: ConfigService, useValue: spy }
]
});
// Inject both the service-to-test and its (spy) dependency
configService = TestBed.get(ConfigService);
configServiceSpy = TestBed.get(ValueService);
});

然后,您可以在测试中使用 spy ,例如:
it('#getValue should return stubbed value from a spy', () => {
const stubValue = 'stub value';
configServiceSpy.getValue.and.returnValue(stubValue);

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

有关更多信息,请查看 Angular Docs 的此部分

关于angular - 引用错误 : Cannot access Service' before initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59665922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com