【问题标题】:How to mock a service that contains a static variable?如何模拟包含静态变量的服务?
【发布时间】:2019-05-06 22:34:31
【问题描述】:

我有一个问题?如何模拟包含静态变量的服务?

这是我的服务

@Injectable()


export class AppConfigService {

    static settings: IAppConfig;
    constructor(private http: HttpClient) {}

    load() {
        const jsonFile = `assets/config/config.${environment.name}.json`;
        return new Promise<void>((resolve, reject) => {
            this.http.get(jsonFile).toPromise().then((response: IAppConfig) => {
                AppConfigService.settings = response as IAppConfig;
                resolve();
            }).catch((response: any) => {
                reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
            });
        });
    }
}

这是我的单元测试代码:

describe('AppConfigService', () => {
    let service: AppConfigService;
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule
            ],
            providers: [
                {provide: AppConfigService, useClass: MockAppConfigService}
            ]});
        service = TestBed.get(AppConfigService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });
    it('should ran load well', () => {
        expect(service.settings)......;
    });

我不能使用service.settings,因为settings是AppConfigService的静态成员……

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:

    你的例子让我很困惑。当您使用模拟覆盖注入器时,您如何测试您的服务。 但仅考虑您的问题,我没有办法知道。不能覆盖对静态成员的访问,只能覆盖其内容。在您的 AppConfigService 示例中,您可以通过在 root 中提供来将此服务限定为单例:

    @Injectable({
      providedIn: 'root'
    })
    

    现在,只要您测试依赖于应用配置的内容,就可以轻松模拟此服务。

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多