javascript - 监视变量的值 - Angular2+

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

});

最佳答案

我不确定你的意思,但你不需要 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/

相关文章:

php - Firefox 'loading' iFrame 提交后轮子继续旋转

javascript - 书签覆盖CSS层?

javascript - jQuery 将事件类添加到第三个动态创建的 div

javascript - FullCalendar-v4 allDay 事件未呈现

javascript - 有没有办法在 TypeScript 2+ 中全局添加类型定义?

javascript - 等待来自 CasperJS 中选择的 <select> 字段的 AJAX 响应

angular - 在 Angular 2 项目中导入和使用带有 Typescript 2 的无类型传单 JS 插件

angular 5路由到相同的组件但不同的参数,不工作

javascript - 我正在尝试制作响应式文本,但无论屏幕有多大,它的大小都是固定的

html - 为任何类型的 HTML 元素键入自定义 useRef Hook