1

I'm running into a unit testing issue with Angular 2 RC5 where it doesn't appear that the ComponentFixture detectChanges method is working the way I expect it to. Here is a snippet of my code:

  describe('Component Test 1', () => {
    beforeEach(async(() => {
      TestBed.compileComponents();
    }));

    it('should calculate base price', async(() => {
      var fixture = TestBed.createComponent(CalcComponent);
      console.log('Got here 1.');
      fixture.detectChanges();
      console.log('Got here 2.');

      expect(fixture.componentInstance.calculateBasePrice()).toBeGreaterThan(50);
    }));
  });

Essentially, when this unit test is run, 'Got here 1.' is printed but the test never goes on to print the second 'Got here 2.' line, and I don't get any sort of useful error message regarding what the error might be. All I get is a very generic message telling me the test failed, even though it clearly never got to the expectation line seeing as how the second console.log line is never printed:

SUMMARY:
√ 9 tests completed
× 1 test failed

FAILED TESTS:
  CalcComponent Tests
    Component Test 1
      × should calculate base price
        PhantomJS 2.1.1 (Windows 7 0.0.0)
      detectChanges
      detectViewChildrenChanges
      detectChangesInternal
      detectChanges
      detectChanges
      detectViewChildrenChanges
      detectChangesInternal
      detectChanges
      detectChanges
      detectChanges
...

I know the problem is around the fixture.detectChanges() line because if I do comment it out, the second console.log prints, and I get an error regarding the expectation failing because of an undefined object (probably since fixture.detectChanges() was never called). Does anyone have an idea of what might be going on here?

benjammin
  • 537
  • 5
  • 23
  • 1
    I think the problem is to do with fixture.detectChanges() where as ComponentFixture.whenStable should be used. I know that TestBed.compileComponents() is async and returns a Promise, therefore there may be some timing issues with detectChnages. The name in theory suggest ComponentFixture.whenStable should solve the problem. Still researching ;) Look at http://stackoverflow.com/questions/38914457/angular-2-testbed-with-mocks – Vishal Sakaria Sep 07 '16 at 12:53

0 Answers0