简体   繁体   中英

Dependency unit testing: Angular 2

I'm trying to create unit tests for my app. What my primary goal is to create a basic spec file for a component or service which just checks if all the services or components on which our component depend are getting imported (that's the most basic spec file I can think of). I tried searching over the internet couldn't come up with something that is useful. Any help will be greatly appreciated.

You should take a look into Angular-Cli . It helps build Angular 2 apps and when you generate a component ng g component my-new-component they automatically create a .spec file for that component. Angular-Cli also sets up the entire Testing Environment as specified HERE .

I don't know how much help this is but maybe it is enough to help you out.

So I have a nav-bar component

blah-nav-bar.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-blah-nav-bar',
  templateUrl: './app/blah-nav-bar/blah-nav-bar.component.html',
  styleUrls: ['./app/blah-nav-bar/blah-nav-bar.component.css']
})
export class BlahNavBarComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
  }

}

And the generated spec file looks like this

blah-nav-bar.component.spec.ts

import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { async, inject } from '@angular/core/testing';
import { BlahNavBarComponent } from './blah-nav-bar.component';

describe('Component: BlahNavBar', () => {
  it('should create an instance', () => {
    let component = new BlahNavBarComponent();
    expect(component).toBeTruthy();
  });
});

I don't know too much about this because I just comment out the spec file, but maybe it is enough to spark something to get you started

UPDATE

I found this on the Official Angular 2 site as well. Here is the link to the Angular 2 Testing home page. It describes Testing a Component with a Dependency

So if you wanted to test an injected service of a component.

app/welcome.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService }       from './model';

@Component({
  selector: 'app-welcome',
  template: '<h3 class="welcome"><i>{{welcome}}</i></h3>'
})
export class WelcomeComponent  implements OnInit {
  welcome = '-- not initialized yet --';
  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.welcome = this.userService.isLoggedIn ?
      'Welcome, ' + this.userService.user.name :
      'Please log in.';
  }
}

The the .spec would look like this

app/welcome.component.spec.ts

import { WelcomeComponent } from './welcome.component';
import { UserService }       from './model';

beforeEach(() => {
  // stub UserService for test purposes
  userServiceStub = {
    isLoggedIn: true,
    user: {
      name: 'Test User'
    }
  };

  TestBed.configureTestingModule({
    declarations: [WelcomeComponent],
    providers: [{
      provide: UserService,
      useValue: userServiceStub
    }]
  });

  fixture = TestBed.createComponent(WelcomeComponent);
  comp = fixture.componentInstance;

  // UserService from the root injector
  userService = TestBed.get(UserService);

  //  get the "welcome" element by CSS selector (e.g., by class name)
  de = fixture.debugElement.query(By.css('.welcome'));
  el = de.nativeElement;


});


// The Tests
it('should welcome the user', () => {
  fixture.detectChanges();
  const content = el.textContent;
  expect(content).toContain('Welcome', '"Welcome ..."');
  expect(content).toContain('Test User', 'expected name');
});

it('should welcome "Bubba"', () => {
  userService.user.name = 'Bubba'; // welcome message hasn't been shown yet
  fixture.detectChanges();
  expect(el.textContent).toContain('Bubba');
});

it('should request login if not logged in', () => {
  userService.isLoggedIn = false; // welcome message hasn't been shown yet
  fixture.detectChanges();
  const content = el.textContent;
  expect(content).not.toContain('Welcome', 'not welcomed');
  expect(content).toMatch(/log in/i, '"log in"');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM