我正在尝试学习如何使用 karma-jasmine 为 angular 2( typescript 文件)创建测试。我的疑问是,要测试 component.ts 文件,我只能测试我在 HTML 文件中调用的方法,还是可以测试所有的方法? 例如:我有这个模型文件 modal.nota.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Nota } from './nota.model'
@Component({
moduleId: module.id,
selector: 'modal-nota',
templateUrl: 'modal.nota.component.html'
})
export class ModalNotaComponent {
test : boolean = true;
setFalse(test) {
this.test = false;
return test;
}
}
而且我没有在我的 HTML 文件中调用方法 'setFalse',但我想测试他。如何调用和测试规范文件中的方法? 模态.nota.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ModalNotaComponent } from '../modal.nota.component';
describe('Test of test variable', () => {
let component: ModalNotaComponent;
let fixture: ComponentFixture<ModalNotaComponent>;
beforeEach(() => {
TestBed.compileComponents(); // ModalNotaComponent test instance
TestBed.configureTestingModule({
declarations: [ ModalNotaComponent ], // declare the test component
});
fixture = TestBed.createComponent(ModalNotaComponent);
component = fixture.componentInstance;
});
it('Should show that the value of test variable is true', () => {
expect(component.test).toBe(true);
});
it('Should test setFalse method', () => {
let r = null;
let t = true;
r = component.setFalse(t);
expect(r).toBe(false);
});
});
此测试无效。我收到这个错误 photo of the errors
最佳答案
经过一些搜索,我找到了如何从 component.ts 文件(服务、模态等)调用方法和变量。您所要做的就是在测试中实例化该类。这是新的测试文件:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ModalNotaComponent } from '../modal.nota.component';
describe('Test of test variable', () => {
beforeEach(() => {
this.modalNota = new ModalNotaComponent();
});
it('Should show that the value of test variable is true', () => {
expect(this.modalNota.test).toBeTruthy()
});
it('Should test setFalse method', () => {
let r = null;
let t = true;
r = this.modalNota.setFalse(t);
expect(r).toBeFalsy()
});
});
致谢:Live chat Developers Blog - Testing Angular 2 apps Part 2: Dependency Injection and Components
关于Angular 2 测试 karma 。具体要测试什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41679349/