Bob Chesley

Bob Chesley's Blog

Mocking the window object in Angular unit tests

Bob Chesley,softwareangularunit testing

In Angular unit tests, you can mock the window object using TestBed and provide a mock value for it. Here's a step-by-step guide on how to do this:

  1. Import the necessary modules and inject the window object into your component/service.

  2. Create a mock window object with the properties and methods you need.

  3. Use the TestBed.configureTestingModule method to configure the testing module, providing the mock window object as a provider.

  4. Instantiate your component or service within the TestBed and run your tests.

Here's an example using Jasmine and Angular TestBed:

import { TestBed } from '@angular/core/testing';
import { YourComponent } from './your.component';
 
describe('YourComponent', () => {
  let component: YourComponent;
 
  beforeEach(() => {
    // Create a mock window object
    const mockWindow = {
      location: { href: 'https://example.com' }, // Example property, add others as needed
      // Add more properties/methods as needed
    };
 
    TestBed.configureTestingModule({
      declarations: [YourComponent],
      providers: [
        // Provide the mock window object
        { provide: Window, useValue: mockWindow },
      ],
    });
 
    // Instantiate the component
    const fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
  });
 
  it('should do something with the window object', () => {
    // Access the component and test its behavior with the mock window object
    expect(component.someMethodUsingWindow()).toBe(/* Expected value */);
  });
});

Replace YourComponent with the name of your component or service, and adjust the mock window object properties and methods according to your needs.

Note: Make sure to provide the mock window object using the useValue property when configuring the testing module. This ensures that Angular injects your mock object instead of the actual window object.

Keep in mind that this is just a basic example, and you may need to customize it based on the specific properties and methods of the window object that your code interacts with.