Published on

Testing exploration for Vue.js

Categorised under

Jest

Installation

To add vue test utils to your existing project, run the following:

vue add unit-jest
npm install --save-dev @vue/test-utils

npm i -g jest-cli
jest filename.spec.js # To run
shell

Mocking time

When I was creating a calendar commponent which makes occasional

Date.now()
calls, There were many solutions which imports external libraries, and tries to mock the system Date implementation. However, for my usecase, it was simpler to create a getCurrentDate method which makes the new Date call within my component, and mock the output of that method.

Here’s a sample implementation of my spec file:

import { shallowMount } from "@vue/test-utils";
import Component from "@/components/Component.vue";
describe("Mock time for each call", () => {
    spy = jest
      .spyOn(DateTimeSelector.methods, "getCurrentDate")
      .mockImplementationOnce(() => new Date("2021-06-01 0:00"));
      .mockImplementationOnce(() => new Date("2021-06-01 1:00"));
    spy.mockRestore();
});
js