1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Unable to test MutationObserver observe() callback

Discussão em 'Angular' iniciado por Ricky, Agosto 15, 2025.

  1. Ricky

    Ricky Guest

    I'm using MutationObserver to detect changes in a DOM element using Angular. Everything is working as expected, but my issue now is how to test if the MutationObserver observe() callback is called.

    This is my current Jest test file:

    describe('MutationObserverDemoComponent', () => {
    let component: MutationObserverDemoComponent;
    let fixture: ComponentFixture<MutationObserverDemoComponent>;

    beforeEach(() => {
    TestBed.configureTestingModule({
    declarations: [MutationObserverDemoComponent]
    });

    fixture = TestBed.createComponent(MutationObserverDemoComponent);
    component = fixture.componentInstance;

    const mutationObserverMock = jest.fn<MutationObserver, [MutationCallback]>().mockImplementation(() => ({
    observe: jest.fn(),
    disconnect: jest.fn(),
    takeRecords: jest.fn()
    }));
    global.MutationObserver = mutationObserverMock;
    });

    it('should observe DOM changes', () => {
    const target = fixture.debugElement.query(By.css('.mutation-div')).nativeElement;

    let observedMutations: MutationRecord[] = [];
    const observer = new MutationObserver((mutations: MutationRecord[]) => {
    console.log('I am not called!'); // this is never called
    observedMutations = observedMutations.concat(mutations);
    });

    observer.observe(target, { attributes: true, childList: true, characterData: true });

    target.setAttribute('data-mutation', 'testing'); // this should trigger the MutationObserver
    expect(observedMutations.length).toBeGreaterThan(0);
    });
    });


    For some reason, the observe() callback isn't being called even though the DOM element is changed. What am I missing here?

    Continue reading...

Compartilhe esta Página