Error in Angular 2.0 final version: Unable to access the 'injector' property of null object

Upon transitioning from Angular 2 RC5 to 2.0 Final, I've encountered some errors while running my tests. It's puzzling me as to what could be causing this issue.

TypeError: Cannot read property 'injector' of null
    at TestBed._createCompilerAndModule (webpack:///Users/mraible/dev/ng2-demo/~/@angular/core/testing/test_bed.js:247:0 <- src/test.ts:20777:44)
    at TestBed._initIfNeeded (webpack:///Users/mraible/dev/ng2-demo/~/@angular/core/testing/test_bed.js:213:0 <- src/test.ts:20743:39)
    at TestBed.createComponent (webpack:///Users/mraible/dev/ng2-demo/~/@angular/core/testing/test_bed.js:297:0 <- src/test.ts:20827:14)

Here is a sample test:

import { MockSearchService } from '../shared/search/mocks/search.service';
import { EditComponent } from './edit.component';
import { TestBed } from '@angular/core/testing/test_bed';
import { SearchService } from '../shared/search/search.service';
import { MockRouter, MockActivatedRoute } from '../shared/search/mocks/routes';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';

describe('Component: Edit', () => {
  let mockSearchService: MockSearchService;
  let mockActivatedRoute: MockActivatedRoute;
  let mockRouter: MockRouter;

  beforeEach(() => {
    mockSearchService = new MockSearchService();
    mockActivatedRoute = new MockActivatedRoute({'id': 1});
    mockRouter = new MockRouter();

    TestBed.configureTestingModule({
      declarations: [EditComponent],
      providers: [
        {provide: SearchService, useValue: mockSearchService},
        {provide: ActivatedRoute, useValue: mockActivatedRoute},
        {provide: Router, useValue: mockRouter}
      ],
      imports: [FormsModule]
    });
  });

  it('should fetch a single record', () => {
    const fixture = TestBed.createComponent(EditComponent);

    let person = {name: 'Emmanuel Sanders', address: {city: 'Denver'}};
    mockSearchService.setResponse(person);

    fixture.detectChanges();
    // verify service was called
    expect(mockSearchService.getByIdSpy).toHaveBeenCalledWith(1);

    // verify data was set on component when initialized
    let editComponent = fixture.debugElement.componentInstance;
    expect(editComponent.editAddress.city).toBe('Denver');

    // verify HTML renders as expected
    let compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h3').innerHTML).toBe('Emmanuel Sanders');
  });
});

To view the pull request showcasing this problem, visit GitHub: https://github.com/mraible/ng2-demo/pull/4

Answer №1

Switching from

import { TestBed } from '@angular/core/testing/test_bed';
to
import { TestBed } from '@angular/core/testing';
resolved the issue in my case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise when compiling Angular 9 with Ivy in a Docker environment

Looking to create a new Angular 9 project using a custom image based on the official node image. I want to cache the package build without caching the Angular source build. Check out my Dockerfile below: FROM node COPY package.json /mnt/ RUN c ...

The ts-mocha test does not play well with the use of node-fetch library

I have set up ts-mocha and node-fetch to run a unit test, but I am encountering the following error: TypeError: Unknown file extension ".ts" for ... The content of the file is as follows: import fetch from 'node-fetch'; export defau ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Bringing in the MVC model class for an ASP.NET Core MVC application paired with an Angular 2 application

Currently, I am developing a sample Angular 2 application alongside ASP.NET Core MVC. I am curious if it is feasible to import a model class (let's say product.cs) that has been created in the "Models" folder directly into the Angular 2 application i ...

Found within the NgModule.imports of ViewClientModule, however, contains errors within the export class SharedModule { }

Recently, I upgraded my Angular project from version 11 to 13. After the upgrade, I encountered an error message "error NG6002: Appears in the NgModule.imports of VerifiedprofilesharedModule, but itself has errors 664 export class SharedModule { }" view i ...

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Which grid systems work well with Angular4, particularly for organizing and refining table data?

Experimented with using ag-grid as it seemed to be the most suitable option. In my package.json, I have the following dependencies: "ag-grid": "^18.1.2", "ag-grid-angular": "^14.0.0", "ag-grid-community": ...

Why am I getting a null value for my Array when I should be expecting an Object instead?

I have been attempting to create an Array that contains objects for a project, but I keep encountering an error message stating: "this.allgmArray is undefined". However, it is not actually undefined: allgmArray: DialogBook[]; [...] load(){ for(var i ...

Using the special character ":" for routing in Angular2

My website URLs follow this pattern: abc.org/books/sort:created/direction:desc abc.org/books/sort:mostviewed/direction:desc abc.com/books/schools/sort:created/direction:desc abc.com/books/schools/sort:mostviewed/direction:desc I am having an issue where ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

The attribute 'sandwiches' cannot be found within the data type 'string'

In my app, I require an object that can store strings or an array of strings with a string key. This object will serve as a dynamic configuration and the keys will be defined by the user, so I cannot specify types based on key names. That's why I&apos ...

Issue: Property is not found within the parameters of the Generic Type

Currently, I am delving into the world of Typescript and have been exploring various exercises that I stumbled upon online. However, I have encountered some trouble with the feedback on incorrect solutions. Specifically, I am facing an issue with the follo ...

Unable to locate partial name

Recently installed the ngx-bootstrap 1.9.2 npm package and encountered an error while trying to compile my Angular project: ERROR in C:/xxx/xx/node_modules/ngx-bootstrap/datepicker/bs-datepicker.component.d.ts (46,15): Cannot find name 'Partial'. ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Resolving the issue of 'type' property missing but required in 'SeriesXrangeOptions' within the Angular Highcharts module

I'm attempting to showcase a price chart view for a specific cryptocurrency chosen from a list of cryptocurrencies, but I keep encountering a type mismatch error. Within my application, I have utilized the angular-highcharts module and brought in the ...

Incorporating jsbi into a TypeScript project while adhering to strict mode

I have been developing a TypeScript library that relies on native BigInts. While it functions perfectly in Chrome, I encountered some issues with Safari. After some research, I stumbled upon the jsbi "polyfill" that seems to solve this problem. Unfortunat ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

The circular reference error message "Redux Action 'Type alias 'Action' circularly references itself" appears

I am currently working with two different actions: export const addToCart = (id: string, qty: number) => async ( dispatch: Dispatch, getState: () => RootState ) => { const { data }: { data: IProduct } = await axios.get(`/api/products/${id}`) ...