[Fixed] Angular jasmine test case for for loop (Error: Expected $.length = 11 to equal 3)

Issue

I’m writing test cases for loop in angular (jasmine) and getting Error: Expected $.length = 11 to equal 3.. For loop suppose to create array of array as in const result. Can anyone please tell what I missed here?
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);

Solution

You need to change your test to call your method and assert that what it does is accurate.

Something like this:

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

Leave a Reply

(*) Required, Your email will not be published