首页 文章

单元测试函数在Angular中的构造函数中调用

提问于
浏览
0

我正在为Angular 2中的服务编写单元测试(参见下面的代码块) . 我如何使用Jasmine框架实现这一目标?

declare var window: any;

@Injectable
export class Somename {

   constructor() {
     if (window.cordova) {
       function1();
     } else {
       function2();
     }
   }

   private function1() {
   }

   private function2() {
   }
}

1 回答

  • 1

    像这样的东西可能是骨架:

    describe('ComponentExample', () => {
      let component: ComponentExample;
      let fixture: ComponentFixture<ComponentExample>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ ComponentExample ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(ComponentExample);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        // Lunch cordova here
        expect(component).toBeTruthy();
        // Not lunch cordova here 
        expect(component).toBeTruthy();
      });
    });
    

    这应该适用于检查构造函数,我不知道如何午餐cordova,因为我没有使用它 . 但是你需要在打开或不打开窗口后期望组件 .

    我读了一些关于ngOnInit的东西,我认为没有必要测试构造函数 . 如果你初始化组件你将测试构造函数,这里的问题是关于open cordova . 检查你是否覆盖了构造函数的一些方法是使用ng test --code-coverage . 这将生成一个带有index.html文件的目录 coverage ,该文件将恢复代码的所有行 . 并说,如果你覆盖某些行或不 .

    当您在应用程序中进行路由时,ngOnInit最常用于执行代码 . 如果您在收取组件或服务时需要执行某些操作,则非常有用 . 但这与此测试没有区别 .

相关问题