[Vuejs]-How to deal with testing that uses uuid inside the component

0👍

Here is a unit test solution for your case:

index.js:

export class SomeClass {
  editableData = {
    jest: []
  };
  $uuid = {
    v1() {
      return 'real uuid';
    }
  };
  addDataItem(key) {
    const basicDataItem = {
      id: this.$uuid.v1(),
      units: '',
      price: '',
      label: ''
    };

    this.editableData[key].push(basicDataItem);
  }
}

index.spec.js:

import { SomeClass } from './';

describe('SomeClass', () => {
  test('should add data item', () => {
    const someClassInstance = new SomeClass();
    const uuidv1Spy = jest.spyOn(someClassInstance.$uuid, 'v1').mockReturnValueOnce('fake uuid');
    someClassInstance.addDataItem('jest');
    expect(uuidv1Spy).toBeCalledTimes(1);
    expect(someClassInstance.editableData).toEqual({ jest: [{ id: 'fake uuid', units: '', price: '', label: '' }] });
  });
});

Unit test result with coverage report:

 PASS  src/stackoverflow/58710736/index.spec.js
  SomeClass
    ✓ should add data item (14ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |    88.89 |      100 |    66.67 |     87.5 |                   |
 index.js |    88.89 |      100 |    66.67 |     87.5 |                 7 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.909s, estimated 6s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58710736

Leave a comment