0

これは、angular2 のドキュメントで提供されているスタブを使用Componentした のテスト例です。Service

ビルドして実行しようとすると、コンポーネントが 2 番目のテスト ケースの変更を反映していないことがわかりました。いつもメッセージを拝見しています。

サービスは次のようになります。

import { Injectable } from '@angular/core';

@Injectable()
export class UserService {
  isLoggedIn: true;
  user: { name: string };
}

コンポーネントは次のようになります。

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

@Component({
  moduleId: module.id,
  selector: 'app-welcome',
  templateUrl: './welcome.component.html'
})
export class WelcomeComponent implements OnInit {
  welcome = '--- not initialized yet';

  constructor (private userService: UserService) {}

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

これは問題の単体テストです:

import { async, TestBed, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { UserService } from './user.service';
import { WelcomeComponent } from './welcome.component';


let fixture: ComponentFixture<WelcomeComponent>;
let comp: WelcomeComponent;
let de: DebugElement;
let el: HTMLElement;
let userService: UserService;

describe('Welcome Component (testing a component with a service)', () => {
  beforeEach(async(() => {
    const userServiceStub = {
      isLoggedIn: true,
      user: {
        name: 'Test User'
      }
    };
    return TestBed.configureTestingModule({
      declarations: [
        WelcomeComponent
      ],
      providers: [
        {
          provide: ComponentFixtureAutoDetect,
          useValue: true
        },
        {
          provide: UserService,
          useValue: userServiceStub
        }
      ]
    }).compileComponents(); // DO NOT USE WITH WEBPACK
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(WelcomeComponent);
    userService = TestBed.get(UserService);
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('.welcome'));
    el = de.nativeElement;
  });

  it('should welcome the user', () => {
    fixture.detectChanges();
    const content = el.textContent;
    expect(content).toContain('Welcome', '"Welcome..."');
  });

  it('should welcome Bubba', () => {
    userService.user.name = 'Bubba';
    fixture.detectChanges();
    expect(el.textContent).toContain('Bubba');
  });

});

エラーは常に次のとおりです。

Expected 'Welcome, Test User' to contain 'Bubba'.

エラー: 「Welcome, Test User」には「Bubba」が含まれている必要があります。

デバッグ中に、サービス スタブが適切な値で更新されていることがわかりました。

4

1 に答える 1