简体   繁体   中英

Mock uuid in jest - uuid called in service function

I have a jest test that is calling the real function and it compares the result returned with an expected result. The service function called uses uuid. I have all kind of errors while trying to mock uuid and can't seem to succeed.

My code is:

import uuid from 'uuid';
import tinyRuleset from './tiny_ruleset.json';
import { Store } from '../store';

describe('TuningStore test ', () => {
  let store;
  let db;

  beforeEach(async () => {
    db = levelup(encode(memdown(), { valueEncoding: 'json' }));
    store= new Store(db);
  });

  test('createObject()', async () => {

    jest.spyOn(uuid, 'v4').mockReturnValue('abc22');

    const obj = await store.createObject();
    expect(obj ).toEqual({
      a: expect.any(string),
      b: 'tiny_ruleset',
      v: expect.any(Function)
    });
  });
})

I tried several ways, but none of them worked. My current error is: uuid is not a function. Also tried this:

const uuidv4Spy = jest.spyOn(store.$uuid, 'v4').mockReturnValueOnce('fake uuid');

Basically uuid is used inside the store.createObject() function.

Thank you!

As explained here Mock uuid

const uuidMock = jest.fn().mockImplementation(() => {
    return 'my-none-unique-uuid';
});
jest.mock('uuid', () => {
    return uuidMock;
});
  • you need to apply the mock in the test file before you are importing your real file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM