首页 > 解决方案 > 错误:必须从注入上下文调用注入(),错误:预期未定义为真

问题描述

我正在为我的 app.component 设置单元测试,我已经导入了所有必要的内容,但是我收到了一个我不明白的错误,在我的 angular.json 中激活“preserveSymlinks”:true 但问题仍然存在,我该如何解决它?

错误: 错误:注入()必须从注入上下文中调用

错误注入

我的 ts 文件:

import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { LoginService } from 'is-common';
import { CookieService } from 'ngx-cookie';
import { Api } from 'is-common';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    title = 'ghai-front';
    isLogged: boolean = false;
    constructor(private router: Router,
        private loginService: LoginService,
        private cookie: CookieService,
        public api: Api) {
        router.events.subscribe((val) => {
            if (val instanceof NavigationEnd)
                this.isLogged = this.loginService.isLogged() === true && val.url !== '/login';
        })
        this.loginService.setApiURL('/api-tacticas');
        this.loginService.setDefaultClient(2);
    }
}

我的测试:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { Api } from 'is-common';
import { LoginService } from 'is-common';
import { HttpClientTestingModule } from '@angular/common/http/testing';


describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    let api: Api;
    let loginService: LoginService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                RouterTestingModule
            ],
            declarations: [
                AppComponent
            ],
            providers: [
                Api,
                LoginService
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        api = TestBed.inject(Api);
        loginService = TestBed.inject(LoginService);
    });

    it('should create the app', () => {
        expect(component).toBeTruthy();
    });
});

我的 tsconfig.app.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "paths": { "@angular/": [ "../node_modules/@angular/" ] }
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

标签: angulartypescriptunit-testingkarma-jasmine

解决方案


我认为问题来自Api,CookieServiceLoginService. 我会模拟这些外部依赖项。

尝试这个:

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    // !! modify these lines !!
    let mockApi: jasmine.SpyObj<Api>;
    let mockLoginService: jasmine.SpyObj<LoginService>;
    let mockCookieService: jasmine.SpyObj<CookieService>;

    beforeEach(() => {
        // Create a new spy before each test
        // The first string is an identifier for the mocked object
        // The array of the strings are public methods
        // I don't know the public methods of API so we will give an empty object
        mockApi = {};
        mockLoginService = jasmine.createSpyObj<LoginService>('LoginService', ['isLogged', 'setApiURL', 'setDefaultClient']);
        mockCookieService = jasmine.createSpyObj<CookieService>('CookieService', ['get']);
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                RouterTestingModule
            ],
            declarations: [
                AppComponent
            ],
            providers: [
                // !! Provide the mocks for all external dependencies
                { provide: Api, useValue: mockApi },
                { provide: LoginService, useValue: mockLoginService },
                { provide: CookieService, useValue: mockCookieService }
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
    });

    it('should create the app', () => {
        expect(component).toBeTruthy();
    });
});

我认为以上内容应该对您有所帮助,并且应该有效。我总是嘲笑外部依赖。


推荐阅读