可以监视变量的值吗?
我想检查执行函数后变量的值是否已更改,即:
应用程序
export class AppComponent {
var someVar = '';
myfunct() {
this.someVar = 'hello world';
}
}
应用规格
let component: AppComponent
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
imports: []
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
it('should equal hello world', () => {
component.myFunct();
expect(component.someVar).toEqual('hello world');
});
最佳答案
我不确定您的意思,但是您不需要茉莉花间谍!
我通常喜欢将角度测试分为两类:
TestBed测试(类似于上面检查UI更改的测试)
非TestBed测试,用于测试组件的纯逻辑。
之所以这样区分,是因为我发现TestBed测试在构建服务器上编写起来较慢,在执行上执行起来也较慢(特别是如果您有很多测试的话)。
您的示例(如果我理解正确的话)属于Non-TestBed类别,因为没有要检查的UI更改(例如绑定和内容)。
一个测试可能看起来像这样:
example.component.ts
export class ExampleComponent {
public someVar: string;
constructor() {
this.someVar = "";
}
public someFunction() {
this.someVar = "Hello World";
}
}
example.component.spec.ts
describe("ExampleComponent", () => {
let component: ExampleComponent;
describe("When the component is initialized", () => {
beforeEach(() => {
component = new ExampleComponent();
});
it("should have a variable someVar that is empty"), () => {
expect(component.someVar).toEqual("");
});
describe("And when someFunction is called", () => {
beforeEach(() => {
component.someFunction();
});
it("should have a variable someVar that is 'Hello World'"), () => {
expect(component.someVar).toEqual("Hello World");
});
});
});
});