Angular 6测试类的模拟依赖

时间:2018-10-21 09:02:52

标签: angular testing jasmine

我是Angular的新手,我已经开始写我的第一个测试。有人可以帮我了解依赖注入的工作原理吗?

我有一个叫做Level.ts的类,它看起来像这样:

export class Level {
 Title: string,
 isTitle: boolean
}

和我实际的名为Previewer.component.ts的组件

import { Input,Component, OnInit } from '@angular/core';
import { Level} from '../Level';

@Component({
  selector: 'app-previewer',
  templateUrl: './previewer.component.html',
  styleUrls: ['./previewer.component.css']
})
export class Previewer implements OnInit {
  @Input() level: Level;

confirmTitle(){
 this.level.Title = "Level 1";
 this.level.isTitle = true;
}
}

我必须补充一点,我当前不使用服务,并且想测试Previewer.component.ts文件。但是,当我运行测试时,它将引发错误,提示“ TypeError:无法读取未定义的属性'isTitle'”。我也使用了NO_ERRORS_SCHEMA,但是仍然出现此错误。 请帮助

我正在测试文件中设置关卡属性

describe('PreviewerComponent', () => {
  let component: PreviewerComponent;
  let fixture: ComponentFixture<PreviewerComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ PreviewerComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(VideoImageTextPreviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    **component.step.HasVideo = false;**
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

我的HTML文件是这样的

<div class="levelPreviewWindow">
                    <div class="mediaBackground" *ngIf="level.isTitle">
                        <video [src]="level.Title" preload="auto" *ngIf="level.isTitle" autoplay controls loop>
                            <source type="video/mp4">
                        </video>
                    </div>
                    <div *ngIf="!level.isTitle">
                        <input type="file" class="mediaUploader" (change)="PreviewVideo($event)">
                    </div>    
                </div>

0 个答案:

没有答案