Angular 角度4茉莉花间谍单元测试“;预期未定义为';新文本';

Angular 角度4茉莉花间谍单元测试“;预期未定义为';新文本';,angular,typescript,jasmine,Angular,Typescript,Jasmine,我有一个简单的函数,可以修改app.component.ts中的一个参数,我想用spy测试这个函数。由于某些原因,我的changeText函数始终未定义。我做错了什么 AppComponent.ts export class AppComponent { text = "My text"; changeText = function () { this.text = "New text"; return this.text; } } d

我有一个简单的函数,可以修改app.component.ts中的一个参数,我想用spy测试这个函数。由于某些原因,我的changeText函数始终未定义。我做错了什么

AppComponent.ts

export class AppComponent {
    text = "My text";

    changeText = function () {
        this.text = "New text";
        return this.text;
    }
}
describe("my text with Spies", function () {  
      it("should be altered", function () {
      const fixture = TestBed.createComponent(AppComponent);
      const app = this.fixture.debugElement.componentInstance;

      spyOn(app, 'changeText');

      expect(app.text).toBe("My text")    
      expect(app.changeText()).toBe("New text");          //Fails
      expect(app.changeText).toHaveBeenCalledTimes(1);
  });
});
AppComponent.spec.ts

export class AppComponent {
    text = "My text";

    changeText = function () {
        this.text = "New text";
        return this.text;
    }
}
describe("my text with Spies", function () {  
      it("should be altered", function () {
      const fixture = TestBed.createComponent(AppComponent);
      const app = this.fixture.debugElement.componentInstance;

      spyOn(app, 'changeText');

      expect(app.text).toBe("My text")    
      expect(app.changeText()).toBe("New text");          //Fails
      expect(app.changeText).toHaveBeenCalledTimes(1);
  });
});

如果这仍然有效,请尝试添加此更改

更改此项:

expect(app.changeText()).toBe("New text");
expect(app.changeText).toHaveBeenCalledTimes(1);
致:


错误是什么?规范失败,错误为“预期未定义为“新文本”,因此changeText的输出因某种原因未定义。可能引用此:可能是范围问题。看起来不错,但您能否在编辑中详细说明为什么这将解决问题?是的,当然。因为您的changeText()方法更改了this.text,因此您应该检查此文本。您还可以编写const text=app.changeText(),然后使用expect(text).toBe(“新文本”)。如果您想检查返回值,我的意思是将此添加到您的答案中。通常尝试描述应该有帮助的代码。它做什么,为什么OP的代码不能工作等。下次。感谢您的建议。