【问题标题】:Angular jasmine test case for for loop (Error: Expected $.length = 11 to equal 3)for 循环的 Angular jasmine 测试用例(错误:预期 $.length = 11 等于 3)
【发布时间】:2021-03-26 17:44:43
【问题描述】:

我正在为 angular (jasmine) 中的循环编写测试用例并获得 Error: Expected $.length = 11 to equal 3.。 For 循环假设在const result 中创建数组数组。谁能告诉我在这里错过了什么? app.ts

loadImages() {
  const rawData = this.data.images;
    for (const value of rawData) {
      for (const image of value.imageData) {
        const v = [value.title, value.documentName, image];
        this.collections.push(v);
      }
    }
}

app.spec.ts

it('should run the loop and push into imageCollection', () => {
      const rawData = component.data.images = [
      {
        'title': 'First Document',
        'documentName': 'Kad',
        'imageData': [
          'one.png',
          'two.png'
        ]
      },
      {
        'title': 'Second Document',
        'documentName': 'Kad',
        'imageData': [
          'three.png'
        ]
      },
    ];
    
    for (const value of rawData) {
      for (const image of value.imageData) {
        const v = [value.title, value.documentName, image];
        component.collections.push(v);
      }
    }
  });
    const result = [
      ['First Document', 'Kad', 'one.png'],
      ['First Document', 'Kad', 'two.png'],
      ['Second Document', 'Kad', 'three.png']
    ];
    expect(component.collections).toEqual(result);

【问题讨论】:

  • 为什么测试中有 for 循环?
  • 我是测试用例的新手。最好的方法是什么?
  • 我的意思是,您正在从测试内部的代码中复制逻辑。那是没有意义的。你应该 1)初始化数据(你已经做了 2)调用方法 component.loadImages() 和 3)做出断言(你也有它)

标签: angular unit-testing karma-jasmine


【解决方案1】:

您需要更改测试以调用您的方法并断言它所做的事情是准确的。

类似这样的:

it('should run the loop and push into imageCollection', () => {
     component.data = {}; // set data property to an object
     component.data.images = [ // populate the images property of the object
      {
        'title': 'First Document',
        'documentName': 'Kad',
        'imageData': [
          'one.png',
          'two.png'
        ]
      },
      {
        'title': 'Second Document',
        'documentName': 'Kad',
        'imageData': [
          'three.png'
        ]
      },
    ];
    
    component.loadImages(); // call loadImages
    const result = [
      ['First Document', 'Kad', 'one.png'],
      ['First Document', 'Kad', 'two.png'],
      ['Second Document', 'Kad', 'three.png']
    ];
    // ensure loadImages is doing what it should be doing.
    expect(component.collections).toEqual(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2015-12-20
    相关资源
    最近更新 更多