26

I have a angularjs component,

HTML template

<div id="panel" class="hide-div">
   <div id="viewPort" class="hide-div">
    ...
   </div>
</div>

JS

var myController = function() {
    var ctrl=this;
    ctrl.$onchanges = function() {

    }

    var source = $("#viewport");
    var target = $("#panel");
    var observer = new MutationObserver(function() {
       target.toggleClass("hide-div", source.hasClass("hide-div"));
     });
    observer.observe($("#viewport")[0], {attributes: true});
}

var config = {
    controller: [myController],
    templateUrl: "temp/abc.html",
    bindings: {
        id: "<",
        name: "<"
    }
};

directives.component("myComponent", config);

Here I have MutationObserver which add/removes the class by observing other elements attribute

Jasmine script Here I am setting up the script for all the test cases

beforeEach(inject(function($rootScope,  $compile, _$componentController_, ...){
    $templateCache.put("temp/abc.html", "<div><div id='panel' /><div id='viewport' /></div>");
    rootScope = $rootScope;
    scope = $rootScope.$new();
    $componentController = _$componentController_;
    element = angular.element("<my-component></my-component>");
    element = $compile(element)(scope);
    ctrl = $componentController("myComponent", null, componentBining);
}));

Here I am getting the following error,

NotFoundError: NotFoundError: DOM Exception 8 in temp/abc.html observe@[native code]

  • try fixing your quotes: $templateCache.put("temp/abc.html", "
    ");
    – BlackICE May 22 '18 at 19:19
  • 1
    I did try it as well as espacing the quote. But it's still throwing same error. –  May 23 '18 at 05:19
  • try to create a plunker (plnkr.co) demonstrating the issue, as it is I can't replicate the problem. – BlackICE May 27 '18 at 14:08
  • Have u tried creating mutation ibserver in global window context? – repo Dec 26 '18 at 22:27
  • You might be able to copy the implementation from JSDOM: https://github.com/jsdom/jsdom/blob/04f6c13f4a4d387c7fc979b8f62c6f68d8a0c639/lib/jsdom/living/mutation-observer/MutationObserver-impl.js#L14 – first last Jan 03 '22 at 13:55

1 Answers1

1

JSDom globals are different from what you would expect.

The answer to this question have to shift the focus from "How to mock MutationObserver?" to "Why to mock it at the first place?"

The MutationObserver is externally implemented for you, and hopefully, it's working just fine. So I wouldn't test it as part of my test scope. Instead I would just extract the callback

const triggerHandler = function() {
       target.toggleClass("hide-div", source.hasClass("hide-div"));
     }

 var observer = new MutationObserver(triggerHandler);

and trigger the handler manually to test the effect.

Also, you can mock the MutationObserver with jest.fn(), like

global.MutationObserver = jest.fn(()=>{
  return {...}
})
Evgeni Dikerman
  • 486
  • 3
  • 18