Day 7: Final Touches and Create tests for some components

For testing the Vue component, we can utilize the Vue Test Utils and Jest. Vue Test Utils allows for mounting Vue components in isolation and simulating user interactions, while Jest can be used for assertions to ensure everything is working as expected.

Firstly, set up your Vue project to use Jest (assuming you’re using Vue CLI):

vue add @vue/unit-jest

Now, let’s write tests for your component. Create a test file ItemsComponent.spec.js:

import { mount } from "@vue/test-utils";
import ItemsComponent from "@/path-to-your-component";  // Replace with the actual path to your component

describe("ItemsComponent", () => {
  let mockFetch = jest.fn();

  // This will replace the global fetch with a mock function for testing
  beforeEach(() => {
    global.fetch = mockFetch;
  });

  it("fetches items on created lifecycle hook", async () => {
    mockFetch.mockResolvedValueOnce(new Response(JSON.stringify([
      { _id: "1", name: "Test Item 1" },
      { _id: "2", name: "Test Item 2" }
    ])));

    const wrapper = mount(ItemsComponent);
    await wrapper.vm.$nextTick();

    expect(wrapper.vm.items).toEqual([
      { _id: "1", name: "Test Item 1" },
      { _id: "2", name: "Test Item 2" }
    ]);
  });

  it("adds an item when 'Add Item' button is clicked", async () => {
    const newItem = { _id: "3", name: "Test Item 3" };
    mockFetch.mockResolvedValueOnce(new Response(JSON.stringify(newItem)));

    const wrapper = mount(ItemsComponent);

    // Simulate adding new item
    await wrapper.setData({ newItem: "Test Item 3" });
    await wrapper.find("button").trigger("click");
    await wrapper.vm.$nextTick();

    expect(wrapper.vm.items).toContainEqual(newItem);
  });

  // Similarly, other tests can be added for edit and delete functionality
});

Note:

  • We’re mocking the fetch function to return predefined values during tests. This way, we won’t make actual API requests during tests.
  • mockResolvedValueOnce allows us to mock the return value of a single fetch call. Multiple mock calls can be chained to simulate various responses in sequence.
  • trigger is used to simulate user interactions with the component.
  • $nextTick is useful to wait for Vue to update the DOM after some data change.

With the above tests, you can test the functionality of fetching items from the backend and adding a new item. Similar approaches can be taken to test the edit and delete functionalities.

When ready, run your tests using:

npm run test:unit

Checkout on github

Post Comment