监视变量的值-Angular2 +

时间:2018-08-02 14:50:08

标签: javascript angular typescript

是否有可能监视变量的值?

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

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

});

1 个答案:

答案 0 :(得分:1)

我不确定您的意思,但是您不需要茉莉花间谍!

我通常喜欢将角度测试分为两类:

  • TestBed测试(与上面检查用户界面更改的测试类似)
  • 非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");
        });
    });
  });
});