Karma / Jasmine:无法测试Angular 4组件内部被调用的服务方法

时间:2018-06-25 18:03:07

标签: angular unit-testing jasmine karma-jasmine

我是karma / jasmine的新手,正在尝试测试其中组件方法调用服务方法并期望返回值的代码。

组件
这是我创建的一个小组件。 在 ngOnInit()中调用 isLoginRequired(),它进一步执行 this.service.checkAuthentication()

export class AppComponent implements OnInit {
  public title = 'app';
  public showLoginBtn = true;

  constructor(private service: CustomService) {}

  ngOnInit() {
    localStorage.setItem('key', '12345');
    this.title = 'name changed';
    this.isLoginRequired();
  }

  isLoginRequired() {
    this.showLoginBtn = this.service.checkAuthentication();
  }
}

服务
这是方法 checkAuthentication()所在的自定义服务。

@Injectable()
export class CustomService {

  constructor() { }

  checkAuthentication(): boolean {
    return !!localStorage.getItem('key');
  }
}

规格
这是我编写单元测试用例的规范文件。请参阅测试案例#4

describe('App component testing', () => {

  let component: AppComponent;
  let service: CustomService;
  let fixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CustomPipe,
        CustomDirective
      ],
      providers: [
        CustomService
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.debugElement.componentInstance;
    service = TestBed.get(CustomService);
  });

  // test case #1
  it('component creation', () => {
    expect(component).toBeTruthy();
  });

  // test case #2
  it('has title "app"', () => {
    expect(component.title).toBe('app');
  });

  // test case #3
  it('isLoginRequired is triggered', () => {
    spyOn(component, 'isLoginRequired');
    component.ngOnInit();
    expect(component.isLoginRequired).toHaveBeenCalled();
  });

  // test case #4
  it('service.checkAuthentication is triggered', () => {
    spyOn(component, 'isLoginRequired');
    spyOn(service, 'checkAuthentication');
    component.ngOnInit();
    expect(component.isLoginRequired).toBeTruthy();
    expect(service.checkAuthentication).toHaveBeenCalled();
  });
});

错误

Error: Expected spy checkAuthentication to have been called.

我真的需要这里的帮助。 预先感谢!

1 个答案:

答案 0 :(得分:0)

spyOn(component, 'isLoginRequired');更改为spyOn(component, 'isLoginRequired').and.callThrough();

默认为不执行Methode。