Frontend Development 14 min read

Why Unit Testing is Needed and How to Write Front‑End Unit Tests with Jest

Unit testing prevents recurring bugs in large front‑end projects by forcing modular, testable code, and with Jest—especially for Vue—developers can quickly write, run, and enforce comprehensive tests covering props, methods, slots, Vuex, and coverage thresholds, while AI tools can scaffold boilerplate test files.

37 Interactive Technology Team
37 Interactive Technology Team
37 Interactive Technology Team
Why Unit Testing is Needed and How to Write Front‑End Unit Tests with Jest

For large, long‑term front‑end projects, the absence of unit tests often leads to recurring bugs when code is maintained by many developers over time. Adding unit tests allows developers to write test code for problem areas, run the tests before each commit, and dramatically reduce the probability of the same bug reappearing. Writing unit tests also forces developers to break complex code into simpler, more testable pieces, which implicitly improves code quality (Test‑Driven Development, TDD).

The typical workflow for a unit test includes four stages:

Preparation – construct parameters, create mocks, etc.

Execution – run the code under test with the prepared inputs.

Assertion – compare the actual result with the expected result.

Cleanup – remove any side effects created during preparation.

In the front‑end ecosystem there are many testing tools; the guide recommends using Jest because it provides assertions, good async support, mocking capabilities, and built‑in code‑coverage reporting.

Jest quick start :

npm install --save-dev jest
# For Vue projects also install Vue Test Utils
npm install --save-dev @vue/test-utils

Example component (PayState.vue):

<template>
  <div class="result-type-wrapper">
    <Icon class="result-icon succ" v-if="state == 'success'"></Icon>
    <p class="result-title">{{ title }}</p>
    <p class="opera-tips">{{ tips }}</p>
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: ['title', 'tips', 'state']
};
</script>

Corresponding Jest test file (payState.test.js):

import payState from '../PayState.vue';
import { shallowMount } from '@vue/test-utils';

describe('payState.vue', () => {
  it('v‑if verification', () => {
    const wrapper = shallowMount(payState, { /* mounting options */ });
    expect(wrapper.findComponent('.result-icon.succ').exists()).toBeFalsy();
  });
});

More comprehensive test examples cover props, computed properties, rendering output, component methods, Vue‑router mocking, mixins, Vuex store interactions, snapshot testing, and coverage thresholds. Below is a condensed example that demonstrates many of these aspects:

import { shallowMount } from '@vue/test-utils';
import CreditCard from '../CreditCard.vue';

jest.mock('@utiles/officialStore', () => ({ RES_HOST: 'mocked-res-host' }));
jest.mock('@store/officialWebStore', () => ({
  GET_CARD_SCHEMES_ACTION: 'mocked-get-card-schemes-action',
  SET_CREDIT_CARD: 'mocked-set-credit-card'
}));
jest.mock('vuex', () => ({ mapState: jest.fn() }));

describe('CreditCard', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallowMount(CreditCard, {
      propsData: {
        curPayType: { currency: 'USD' },
        curLocationVal: 'mocked-location',
        discountTransMount: 100,
        curCoins: { TRANS_AMOUNT: 50 },
        isCoins: true
      },
      mocks: {
        $store: {
          state: { gameId: 'mocked-game-id' },
          commit: jest.fn(),
          dispatch: jest.fn()
        },
        window: { webstorev2DataLayer: { push: jest.fn() } }
      },
      slots: {
        default: '
Default Slot Content
',
        namedSlot: '
Named Slot Content
'
      },
      scopedSlots: {
        contextualSlot: '
Contextual Slot Content
'
      }
    });
  });

  it('renders the component', () => {
    expect(wrapper.exists()).toBe(true);
  });

  // ... (additional test cases for props, computed, methods, router, mixins, Vuex, snapshots)

  it('renders the default slot content', () => {
    expect(wrapper.find('.default-slot').exists()).toBe(true);
    expect(wrapper.find('.default-slot').text()).toBe('Default Slot Content');
  });
});

Test reports and coverage:

Statement coverage – has every statement been executed?

Branch coverage – has every if/else branch been exercised?

Function coverage – has every function been called?

Line coverage – has every line of code run?

Jest can be configured to enforce an 80 % global coverage threshold:

coverageThreshold: {
  global: {
    branches: 80,
    functions: 80,
    lines: 80,
    statements: 80
  }
},

Finally, the guide suggests using AI (e.g., LangChain) to generate boilerplate Jest test code for Vue components, reducing repetitive effort. A sample generated test file is shown below:

import { shallowMount } from '@vue/test-utils';
import CreditCard from '../CreditCard.vue';

jest.mock('@utiles/officialStore', () => ({ RES_HOST: 'mocked-res-host' }));
jest.mock('@store/officialWebStore', () => ({
  GET_CARD_SCHEMES_ACTION: 'mocked-get-card-schemes-action',
  SET_CREDIT_CARD: 'mocked-set-credit-card'
}));
jest.mock('vuex', () => ({ mapState: jest.fn() }));

describe('CreditCard', () => {
  // ... generated test cases for render, methods, computed, watch, slots, etc.
});

The AI‑generated tests provide a solid starting point, after which developers can add business‑specific assertions and logic.

frontendAutomationunit testingVuejesttest coverage
37 Interactive Technology Team
Written by

37 Interactive Technology Team

37 Interactive Technology Center

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.