我試圖監視來自 uuidv4 包的函式,但我不知道該怎么做。
這是我的用戶類:
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();
}
}
我要做的是監視在 User.ts 的建構式上呼叫的 uuid() 方法。我試過這樣的事情:
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);
});
});
但它沒有用。任何人都知道我該怎么做?
uj5u.com熱心網友回復:
您無需模擬或安裝 spyuuid即可測驗實作細節。您可以使用正則運算式來測驗是否user.id是 UUID v4。
使用正則運算式:
如果您想使用正則運算式自行執行驗證,請使用 regex 屬性,并訪問其 v4 或 v5 屬性
index.ts:
import { uuid } from 'uuidv4';
interface IUser {
id?: string;
}
export class User implements IUser {
constructor(public name: string, public email: string, public password: string, public id?: string) {
this.id = id ? id : uuid();
}
}
index.test.ts:
import { User } from './';
import { regex } from 'uuidv4';
describe('User', () => {
it('should call uuid() when no id is provided', () => {
const user = new User('Foo', '[email protected]', '12345');
expect(regex.v4.test(user.id!)).toBeTruthy();
});
});
PASS stackoverflow/72130740/index.test.ts (13.885 s)
User
? should call uuid() when no id is provided (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 16.53 s
還要看一下uuid 測驗用例
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475375.html
