gpt4 book ai didi

angular - 单元测试因 Angular 中的 NullInjectorError 而失败

转载 作者:行者123 更新时间:2023-12-05 05:11:42 26 4
gpt4 key购买 nike

我是 Angular 的新手,在理解 DI 的工作原理时我遗漏了一些东西。我目前正在尝试通过单元测试。

下面是测试代码;

import { TestBed } from '@angular/core/testing';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { InjectionToken } from '@angular/core';
import { UserService } from './user.service';

export const BASE_URL = new InjectionToken<string>('BASE_URL');

describe('UserService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
],
providers: [
{ provide: BASE_URL, useValue: 'http://localhost' },
UserService,
HttpClient
]
}));

it('should be created', () => {
const service: UserService = TestBed.get(UserService);
expect(service).toBeTruthy();
});
});

这是被测代码;

import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { User } from '@/_models';

@Injectable({ providedIn: 'root' })
export class UserService {

private baseUrl: string

constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.baseUrl = baseUrl
}

getAll() {
return this.http.get<User[]>(`${this.baseUrl}/users`);
}

getById(id: number) {
return this.http.get(`${this.baseUrl}/users/${id}`);
}

register(user: User) {
return this.http.post(`${this.baseUrl}/users/register`, user);
}

update(user: User) {
return this.http.put(`${this.baseUrl}/users/${user.id}`, user);
}

delete(id: number) {
return this.http.delete(`${this.baseUrl}/users/${id}`);
}
}

这是我的错误;

Error: StaticInjectorError(DynamicTestModule)[BASE_URL]:
StaticInjectorError(Platform: core)[BASE_URL]: NullInjectorError: No provider for BASE_URL!

为什么会出现此错误,我需要采取什么措施来纠正它?

最佳答案

替换{ provide: BASE_URL, useValue: 'http://localhost' }{ provide: 'BASE_URL', useValue: 'http://localhost'}

关于angular - 单元测试因 Angular 中的 NullInjectorError 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55261912/

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