gpt4 book ai didi

javascript - 监视变量的值 - Angular2+

转载 作者:行者123 更新时间:2023-12-03 01:23:24 25 4
gpt4 key购买 nike

是否可以监视变量的值?

我想检查执行函数后变量的值是否已更改,即:

app.ts

export class AppComponent {
var someVar = '';

myfunct() {
this.someVar = 'hello world';
}
}

app.spec.ts

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');

});

最佳答案

我不确定你的意思,但你不需要 Jasmine spy !

我通常喜欢将 Angular Testing 分为两类:

  • TestBed 测试(类似于上面检查 UI 更改的测试)
  • 非 TestBed 测试,用于测试组件的纯逻辑。

我做出这样的区分是因为我发现 TestBed 测试的编写速度较慢,在构建服务器上执行的速度也较慢(特别是如果您有很多测试)。

您的示例(如果我理解正确的话)属于非 TestBed 类别,因为没有需要检查的 UI 更改(如绑定(bind)和内容)。

测试可能如下所示:

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");
});
});
});
});

关于javascript - 监视变量的值 - Angular2+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com