【问题标题】:Angular Unit Testing : Expect undefined to equal true角单元测试:期望未定义等于真
【发布时间】:2020-04-16 18:56:23
【问题描述】:

我是编程新手,这是我第一次被要求在 Angular 中进行单元测试,我有点困惑...... 我想在我的 component.ts 中测试这个方法:

isInputHidden = true;

showInput(){this.isInputHidden = false;}

spec.ts:

it('should show the input', () => {
component.isInputHidden == false;
let showInput = component.showInput();
expect(showInput).toBe(true);

})

当我运行这个测试时,我得到了这些错误: In jasmine ==> Expect undefined to equal true。 在终端 ==> 类型“真”的参数不能分配给“预期”类型的参数。 有人可以帮我弄清楚我应该改变什么?

【问题讨论】:

  • 你必须在 showInput() 中返回 sthg(例如 this.isInputHidden)来初始化 showInput

标签: angular typescript unit-testing


【解决方案1】:

以下是修复测试的方法:

  • = 而不是== 初始化你的变量
  • 直接调用函数(你不能用它初始化 showInput 变量,因为函数不返回任何东西)
  • 要测试的预期变量是 InputHidden,因为您使用 showInput() 函数更改了它的值
it('should show the input', () => {
component.isInputHidden = false; // removed a "="
component.showInput(); // your function will change isInputHidden directly
expect(component.isInputHidden).toBe(true); // test isInputHidden

【讨论】:

  • 它工作...我只需要通过 toEqual(false) 更改 toEqual(true),因为在这种情况下我们正在讨论 isInputHidden 参数...谢谢:)
  • true 我颠倒了值抱歉
  • no pb... 但是当我尝试测试另一种情况时它不起作用(isInputHidden = false; expect()tobe(true) ==>Expected false to be true... . 我想我需要设置变量不是吗?
  • 因为您的属性为假,showInput() 也将其设置为假,所以您无法期望它为真
  • 你需要一个 hideInput(){this.isInputHidden = true} 才能将你的属性设置为 true
猜你喜欢
  • 1970-01-01
  • 2019-12-09
  • 2019-12-10
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
相关资源
最近更新 更多