1

I would like to write a unit test to test if the expectedData is showing as expected. The HTML code is working and it displays everything correctly.

HTML code:

<div class="col-6 p-0 LHS" *ngIf="data && data.type === 'App'">
  <div *ngFor="let d of data">
    <div class="row">
      <div class="col-auto">Item1:</div>
      <div class="appItem1">{{d.item1}}</div>
    </div>
  </div>
</div>

TS file:

  data = [{item1: "Item 1", item2: "Item 2"}, type: "App", display: true]; // sample input data
  expectedData;

  getExpectedData() {
    if (this.data && this.data.item) {
      switch (this.data.type) {
        case ("File"):
           this.expectedData = $('.fileItem1')[0].innerHTML;  
          break;
        case ("App"):
          this.expectedData = $('.appItem1')[0].innerHTML;              
          break;
      }
    }
  }

My test case:

it('should verify expected data', () => {
    const mockdata= [{item1: "Item 1"}];
    mockdata.type= 'App'; // getting error because this can't be pushed to array
    mockdata.display= true; // getting error because this can't be pushed to array
    component.data = mockdata;
    fixture.detectChanges();
    component.getExpectedData();
    expect(component.expectedData).toBe("Item 1");
  });

However, in my test case, it doesn't seem to be working to mock the data to that type of data, are there any possible way to test the getExpectedData()?

Thanks

8
  • So what is the problem? You dont know how to push object into an array ? Commented Jan 6, 2021 at 17:30
  • I data actually an array or an object? Commented Jan 6, 2021 at 17:32
  • @Antoniossss The problem is I'm not able to mock that data to test that method. It's an array but with the json data which is confusing, so I couldn't create the test data. Commented Jan 6, 2021 at 17:38
  • your code shows its not an array but an object. See this this.data.type?? This is how you access object's properties, not array elements. Commented Jan 6, 2021 at 17:49
  • Mocking is not a problem as it will work just as you try to do it. The problem here is broken data model. Commented Jan 6, 2021 at 17:54

1 Answer 1

1

I have no idea why you have a mutated array, but so be it. The one of the answers is to use

//@ts-ignore

const mockdata= [{item1: "Item 1"}];
//@ts-ignore
mockdata.type= 'App'; 
//@ts-ignore
mockdata.display= true; 
component.data = mockdata;

https://stackblitz.com/edit/typescript-ae5pvs?file=index.ts

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.