Angular 2 unit testing - getting error Failed to load 'ng:///DynamicTestModule/module.ngfactory.js'

前端 未结 10 2387
执念已碎
执念已碎 2020-12-23 11:04

I have angular 2 webpack application, all webpack,karma configuration created as per angular.io webpack guide. I am not using aot. I am writing jasmine unit test spec to te

10条回答
  •  悲&欢浪女
    2020-12-23 11:43

    I also had this issue and it was due to malformed mocked data. In my component I had a service which made a http call.

    something like: (service code)

    getData() {
       return this.http.get(obj);
    }
    

    In the component I called this function and subscribed to it: (component code)

    this.service.getData().subscribe((data) => {
      this.componentData = data.things; //**<=== part that broke everything**
    }, (error) => {
      console.log(error);
    });
    

    Solution:

    When I mocked out the service function I failed to return data that had the attribute things. This is what caused the XMLHttpRequest failure, I guess to angular it looked like the error happened as if it was the HTTP request. Making sure that I returned the correct attributes on any mocked HTTP requests fixed the issues.

    Hope this clears things up. Below is the code for the implementation of the mock.

    (component.specs)

    function fakeSubscribe(returnValue,errorValue) {
      return {
        subscribe:function(callback,error){
          callback(returnValue);
          error(errorValue);
        }
      }
    }
    
    
    
     class MockService {
          getData() {
            var fakeData = {
              things:[]
            }
            return fakeSubscribe(fakeData,0);
          }
       }
    

提交回复
热议问题