Simple Jest Snapshot for Angular Component

Below is a simple jest snapshot with an interface for the list items and three signal inputs.

Points to Note

  • The “render” function comes from the “@testing-library/angular”.
  • Not passing the second argument may cause lint errors or miss leading co-pilot suggestions.
  • Using the “render” function allows you the nice approach of setting the inputs.
import { render } from '@testing-library/angular';
import { QueueListComponent } from './queue-list.component';

interface QueueItem {
  id: string;
  name: string;
  isSource: boolean;
  mode: string;
}

const mockQueues: QueueItem[] = [
  {
    id: '1',
    name: 'Alice Johnson',
    isSource: true,
    mode: '',
  },
  {
    id: '2',
    name: 'Bob Smith',
    isSource: false,
    mode: '',
  },
];

describe('QueueListComponent', () => {
  it('renders consistently', async () => {
    const { container } = await           render(QueueListComponent, {
      inputs: {
        queues: mockQueues,
        primaryLabel: 'Primary Queue',
        secondaryLabel: 'Secondary Queue',
      },
    });

    expect(container).toMatchSnapshot();
  });
});

Elaboration on the Points Above

Point One

Using the “render” function for a snapshot was the suggestion of chat-gpt, it was the alternative to using the standard testbed, testbed was recommended when needing deeper integration with services and logic.

What Chat-GPT had to say

Point Two

When I first got the suggestion from GPT, it did not give me the second arg (inputs in this case) and I was getting errors telling me about my component not being recognised, I initially opted for a co-pilot suggestion and it converted the component to a string containing the selector with the inputs passed in as if I was using it in a parent component, I cannot replicate this now, the second param of the “render” function is optional either way. (I wasn’t having the best day :/ )

Point Three

I liked that I could just declare the required inputs as shown above with “render” function options, it seems a bit cleaner than the only way I currently now when you use the “Testbed” approach.

Signal Input from the Class

inputData = input.required<IItem>();

Spec File Code to Set the Input

fixture = TestBed.createComponent(ExamplePanelComponent);
component = fixture.componentInstance;

fixture.componentRef.setInput('inputData', mockItem('Example'));

Last Things to Remember

To generate the snapshot, I was running “npx jest” this should highlight that your snapshot was created in green along with tests run, etc.

This post was generated as a memory jogger, if you’ve found it, I hope it helps you out

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *