Testing the injection of ChangeDetectorRef using pipesWould you like to test the

I am working with a pipe that looks like this:

@Pipe({name: 'myPipe', pure: false})
export class MyPipe implements PipeTransform {

    constructor(private _ref:ChangeDetectorRef) {
         _ref.markForCheck();
    }

    public transform(input: string | number) {
         return 'something';
    }

}

Below is my test specification for the pipe:

describe('Pipe: MyPipe', () => {
    let changeDetector: ChangeDetectorRefMock;
    let pipe: MyPipe;
    beforeEach(async() => {
        await TestBed.configureTestingModule({
            providers: [
                MyPipe,
                {
                    provide: ChangeDetectorRef,
                    useClass: ChangeDetectorRefMock
                }
            ];
        }).compileComponents();
        changeDetector = TestBed.inject(ChangeDetectorRef) as ChangeDetectorRefMock;
        pipe = TestBed.inject(MyPipe); // <-- error is thrown (see below)
    });

    it('should create', () => {
        expect(pipe).toBeTruthy();
    });
});

@Injectable()
class ChangeDetectorRefMock {
    public detectChanges(): void {}
}

When running the test spec, I encounter an error at line pipe = TestBed.inject(MyPipe);:

TypeError: Cannot read properties of null (reading 'type')
    at createViewRef (C:\interne\VEBLuZ\packages\core\src\change_detection\change_detector_ref.ts:163:20)
    [...]
    at C:\exampleProject\libs\example-lib\src\pipe\my.pipe.spec.ts:22:20

Do you have any suggestions on how to properly test this pipe with injection of ChangeDetectorRef?

Answer №1

The solution is straightforward! Instead of injecting a pipe, you can generate it using its constructor:

 newPipe = initializeNewPipe(changeDetector);

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

Issue: Unhandled promise rejection: SecurityError: To use screen.orientation.lock(), the page must be in fullscreen mode

While attempting to change the orientation of one of my pages in an Ionic 3 app, I encountered the following error. The code snippet below was used to change from portrait mode to landscape mode: ionViewDidEnter() { // this.statusBar.hide(); // // ...

Is there a method to tidy up this sequence of rxjs operators?

I have a complex stream of Rxjs piped observables that I'm working with. Everything seems fine at first, but things start to get a bit crazy when I reach a certain point in the code. //THIS IS WHERE IT STARTS GETTING A BIT CRAZY At this stage, if t ...

Is it feasible to obtain the userId or userInfo from the Firebase authentication API without requiring a login?

Is it feasible to retrieve the user id from Firebase authentication API "email/password method" without logging in? Imagine a function that takes an email as a parameter and returns the firebase userId. getId(email){ //this is just an example return t ...

I'm having trouble with class attributes not functioning properly in TypeScript within Angular. What steps can I take to resolve this issue

Currently, I am in the process of mastering Angular, CSS (particularly Tailwind), HTML, and TypeScript as a means to construct a website. Despite clicking the menu button on the navigation bar thrice, I was puzzled why this.name appeared as undefined duri ...

Can Google.com be tested using Angular CLI?

Is it possible to conduct a simple Google search test using Angular CLI? How can I change the default localhost to an "outside" web location? Thanks in advance, (I am new to CLI and still learning, so any help is appreciated!) Best regards to all! ...

Utilizing properties in a fresh function with Angular 2

Having an issue with the beacon Minor propriety in a new function. The editor keeps saying that the name cannot be found, and I'm not sure how to resolve it. Function Example: listenToBeaconEvents() { this.events.subscribe('didRangeBeacons ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...

What is the best way to trigger a function from a component (<menu></menu>) and pass the resulting data to another component efficiently?

This particular query may appear familiar, but surprisingly I am still unable to find a solution that will make my code function properly. The issue lies within the implementation of routes in my application. Specifically, I have 2 key components: MenuComp ...

Retrieve information from matSnackBar using openFromComponent

Hello there! As a newcomer to Angular, I am interested in retrieving data from matsnackbar. Is this something that can be achieved? apiName: string; this.snackBar.openFromComponent(CustomSnackbarComponent, { duration: 5000000, dat ...

Guide on displaying console.log in mobile simulator while using Angular2

Interested in debugging JavaScript on mobile devices, particularly Android and iPhone. Seeking a code snippet or library that can display console.log messages on the screen of a phone emulator. Ideally looking for a solution that works with angular2 and i ...

The error type currently displayed relates to window['angularComponentReference']

Currently, I am attempting to incorporate NgZone into my Angular project: constructor( private fishboneService: FishboneService, private zone: NgZone, ) { window['angularComponentReference'] = { zone: this.zone, componentFn: (val ...

Troubleshooting Cross-Origin Resource Sharing (CORS) issue with Angular, Maven

I have been working on setting up an application with an Angular front-end and a Maven/Spring Boot backend. I've created my first REST controller, but when I attempt to send a GET HTTP request from my Angular IDE to the backend, I receive the followin ...

Tips for including a background image using the :after pseudo-element in Angular 2

I'm facing a challenge with passing a URL image from my HTML to my CSS in Angular, and I can't seem to figure it out: Here is a snippet of my CSS: card-profile_visual { height: $visual-height; overflow: hidden; position: relat ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

What is the best way to assign values to all properties of a TypeScript class?

I am working on a class that has private properties: class A implements IA { private id: number; private name: string; constructor(obj: IA) { // Need to assign properties from obj here } } My goal is to pass an object of type IA with i ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

Getting response headers in Angular by utilizing an HTTP interceptor

Seeking guidance on how to interpret response headers when utilizing httpinteceptor in Angular. I have exposed all the tokens in my Node.js application, but am facing challenges in comprehending all the keys passed in the response headers. intercept(req: ...

What drawbacks come with developing an Express.js application using TypeScript?

Curious about the potential drawbacks of using TypeScript to write Express.js applications or APIs instead of JavaScript. ...

Ways to troubleshoot issues with the ng bootstrap package

Having an issue debugging ng-bootstrap 4 in my Angular 7 project, I decided to follow the instructions provided on this link to clone ng-bootstrap and install dependencies using yarn. The process completed without any errors. However, when attempting to np ...

Add aesthetic flair to scrollable containers

I am currently working on displaying data in columns using ngFor. However, I've run into an issue where the styles I apply to the column div are only visible on the top part of the column. As I scroll down to the bottom, the styles disappear. I believ ...