0

In angular 1, if I wrote a component, I would make sure that:

  • Dependencies, such as services is being mocked.
  • Unit tests are written for methods within the component.
  • The component is calling the service to retrieve the data expect(service.method).toHaveBeenCalled()
  • The component is updating the view given an updated model.

I've been doing some research on Angular 2 component testing, and for all the articles I can find, it seems that testing is being done as follows;

  • Create a service mock that returns a fixed result (ex: 'Test Quote')
  • Expect that the view contains the result coming from the mocked service (ex; that there's a div somewhere that has <div>Test Quote</div>).

Here are a few examples of such articles (basically top results on google for 'Angular 2 Component Testing')

Since NG2 provides no spies in it's testing framework @angular/core/testing, it's recommended to avoid the step in bold altogether? Or should we be including jasmine to just have access to spies?

1 Answer 1

0

if you are specifically looking to test component rendering, then you can use TestComponentBuilder as explained in blogs mentioned in your question.

    describe('MyComponent', () => {

      it('should render list', async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb.createAsync(MyComponent).then((componentFixture: ComponentFixture) => {
          const element = componentFixture.nativeElement;
         //... get the element you want to check 
          componentFixture.detectChanges();
          expect(element).toHaveText('test div');
          expect(element.querySelectorAll('div').length).toBe(1);
        });
      }));    
}));

if a service is being called in component then you want to inject in beforeEachProviders() or beforeEach() method like :

beforeEach(() => {
    addProviders([
      provide(LoginService, { useClass: MockLoginService }),
      UserService
    ]);
  });

using jasmine spies along with methods like and.callThrough and and.returnValue is very useful when you want to mock a service call in component. Additionally, have a look at this repo by angular team member julie raplh.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.