I'm trying to spy on a function that come from uuidv4 package but I didn't figure out how to do that.
This is my User Class:
import { uuid } from 'uuidv4';
import { IUser } from '../interfaces/IUser';
export class User implements IUser {
constructor(
public name: string,
public email: string,
public password: string,
public id?: string,
) {
this.id = id ? id : uuid();
}
}
What I'm trying to do is spy on that uuid() method that is called on the constructor of the User.ts. I tried something like this:
import { User } from './User';
describe('User', () => {
it('should call uuid() when no id is provided', () => {
const sut = new User('Foo', '[email protected]', '12345');
const spy = jest.spyOn(sut, 'uuid');
expect(spy).toHaveBeenCalledTimes(1);
});
});
But it didn't work. Anyone knows how could I do this?
You don't need to mock or install spy on the
uuidto test the implementation detail. You can test the with Using a regular expression to checkuser.idis a UUID v4 or not.Using a regular expression:
index.ts:index.test.ts:Also take a look at the
uuidtest case