Programing

'XMLHttpRequest'에서 '보내기'를 실행하지 못해 각도 테스트 실패

lottogame 2020. 6. 28. 18:29
반응형

'XMLHttpRequest'에서 '보내기'를 실행하지 못해 각도 테스트 실패


각도 4.1.0 구성 요소를 테스트하려고합니다.

export class CellComponent implements OnInit {
  lines: Observable<Array<ILine>>;
  @Input() dep: string;
  @Input() embedded: boolean;
  @Input() dashboard: boolean;
  constructor(
    public dataService: CellService,
    private route: ActivatedRoute,
    private router: Router, private store: Store<AppStore>) {
  }
}

그러나 간단한 "만들어야한다"테스트는이 중대한 오류를 발생시킨다.

NetworkError : 'XMLHttpRequest'에서 '보내기'를 실행하지 못했습니다 : 'ng : ///DynamicTestModule/module.ngfactory.js'를로드하지 못했습니다.

그래서 나는 발견 문제가 구성 요소가있다는 것을 시사 문제, @Input)_내가 지금처럼 내 테스트를 수정하는 경우, 그러나, 설정되지 않은 PARAMS를 :

  it('should create', inject([CellComponent], (cmp: CellComponent) => {
    cmp.dep = '';
    cmp.embedded = false;
    cmp.dashboard = false;
    expect(cmp).toBeTruthy();
  }));

그런 다음 @Input()구성 요소 에서 주석을 제거해도 여전히 동일한 문제가 발생 합니다. 이 시험에 합격하려면 어떻게해야합니까?


이것은 새로운 Angular Cli의 문제입니다. 테스트를 실행 --sourcemaps=false하면 올바른 오류 메시지가 표시됩니다.

자세한 내용은 여기를 참조하십시오 : https://github.com/angular/angular-cli/issues/7296

편집하다:

이에 대한 속기는 다음과 같습니다.

ng test -sm=false

각도 6에서 명령은 다음과 같습니다.

ng test --source-map=false


angualar cli 6을 사용하는 것과 동일한 문제가 발생했습니다.이 태그를 사용하여 올바른 오류 메시지를 얻었습니다.

ng test --source-map=false

어쩌면 그것은 누군가를 도울 것입니다 :).


내 경우에는 모의 데이터 문제가 있었고의 경우 모의에서 Array돌아 왔습니다 string.

someApi = fixture.debugElement.injector.get(SomeApi);
spyOn(someApi, 'someMethod')
  .and.returnValue(Observable.of('this is not a string but array'));

오류 메시지가 실제로 산만하고 실제 오류를 알리지 않았습니다. Running ng test --source=false은 올바른 오류와 줄을 가리키고 신속하게 수정하는 데 도움이되었습니다.

데이터를 모의하는 것이 불완전하거나 올바르지 않은 경우 여러 번 발생합니다.


component.ts 에서 input () 속성을 기본값으로 설정할 수 있습니다

@Input() tableColumns: Array<any> = [];  
@Input() pageObj: any = '';

또는

다음과 같이 component.spec.ts 파일을 수정하십시오 .

beforeEach(() => {  
   fixture = TestBed.createComponent(MyComponent);  
   component = fixture.componentInstance;  
   component.tableColumns = [];  
   component.pageObj = '';  
   fixture.detectChanges();  
});

As suggested above here: https://stackoverflow.com/a/45570571/7085047 my problem was in my ngOnInit. I was calling a mock swagger-generated REST controller proxy. It was returning null, and I was subscribing to that null, which doesn't work...

The error came back:

Failed to load ng:///DynamicTestModule/MockNodeDashboardComponent_Host.ngfactory.js: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I fixed the issue using ts-mockito: https://github.com/NagRock/ts-mockito

I added code to create a mock instance like this:

import { mock, instance, when } from 'ts-mockito';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { MockScenario } from './vcmts-api-client/model/MockScenario';

const MockVcmtsnodemockresourceApi: VcmtsnodemockresourceApi = mock(VcmtsnodemockresourceApi);
const obs = Observable.create((observer: Observer<MockScenario[]>) => {
  observer.next(new Array<MockScenario>());
  observer.complete();
});
when(MockVcmtsnodemockresourceApi.getMockScenariosUsingGET()).thenReturn(obs);
const instanceMockVcmtsnodemockresourceApi: VcmtsnodemockresourceApi = instance(MockVcmtsnodemockresourceApi);

And then added the instance to the test's providers array like this:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      ...
      providers: [
        ...
        { provide: VcmtsnodemockresourceApi, useValue: instanceMockVcmtsnodemockresourceApi },
        ...
      ]        
    }).compileComponents();
  }));

This can be related to Chrome hiding an actual test error. The test area will be confusing some mock http factory that it can't load and therefore that is the error it will report. Most likely the error will be around the ngOnInit area where an object is, say, expecting sub objects and they are not defined.

To try and get to the bottom of the error, switch to PhantomJS temporarily which seems to suffer less from these initialisation errors and this will hopefully report the actual error to you. Several occasions I found to be where an object expected on initialisation wasn't complete. IE:

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

    component.object = {}
// should be:
    component.object = {"innerObjectThatIsNeeded" : []}

Correcting the object allowed PhantomJS to complete and also Chrome to move on to the next test.

Other than that I've not seen a solution to remove the issue from Chrome. As ever try and adopt a "remove the code, until error goes" policy to chase down the error.


I also had this error, which truth be told is fairly non talkative.

It was related to the HTTP calls trough my services

I use myService.ts with 2 methods

get();
getAll();

I am mocking this service : mockMyService.ts

The error was here because my component was using getAll() method that I forgot to implement in the mockMyService, so I just added the method :

private mockObjects = [
{
  'id': '1',
  'champ1': 'TECH',
  'champ2': 2,
  'champ3': 'Data bidon'
},
{
  'id': '2',
  'champ1': 'TECH',
  'champ2': 2,
  'champ3': 'Data au pif'
},
{
  'id': '3',
  'champ1': 'FUNC',
  'champ2': 3,
  'champ3': 'Data quelconque'
},
 ];

getAll(): Observable<any> {
  return Observable.of(this.mockObjects);
}

Error was gone :)


I faced the same issue and I've found out that to fix it you have to set your inputs for the component in the method beforeEach as shown below:

beforeEach(() => {
    fixture = TestBed.createComponent(CellComponent );
    cmp = fixture.debugElement.componentInstance;
    cmp.dep = '';
    cmp.embedded = false;
    cmp.dashboard = false;
    fixture.detectChanges();
});

This will definitely resolve your issue.


In my case the culprit was observable.timeout(x).retry(y) applied somewhere on the returned Observable on the service class level, then again in the component which was using that service.

Everything worked correctly in the browser up until angular-cli 1.4. Then started failing during Karma tests (with such a silly error). The solution was of course to tidy up these timeout/retry operators.


For me this message appear when a mock is falsy in my tests : usually you provide mockService in your tests bootstrap. If your mock is incomplete or falsy, then angular return this stupid error.

More information on my case here


What I would be doing is:

Add console.log() s, line after line in ngOnint() and find out how far it goes , then inspect the line which it wont pass through.

Ex:

ngOnInit() {
    this.route.paramMap
        .switchMap(params => {
            this.busy = true;
            this.updateErrors(null);

            console.log(params);

            **const id = params.get('id');**
            console.log(id);

            if (id === 'new') {
                this.editMode = true;
                return Observable.of(GroupComponent.newGroup());
            }
            return this.apiService.getGroup(id);
        })
    }

This was failing on my test with the same error in this post. As shown above, I had two console.logs. First one passed thorugh , but the second one not. So I realized the issue is on line const id = params.get('id'); and I fixed it.

Hope this will help someone.

참고URL : https://stackoverflow.com/questions/45399079/angular-tests-failing-with-failed-to-execute-send-on-xmlhttprequest

반응형