如何使用 Jest 和 Typescript 监视不属于被测 class 的函数

How to spyOn a function that is not part of the class under test with Jest and Typescript

我正在尝试监视来自 uuidv4 包的函数,但我不知道该怎么做。

这是我的用户 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();
  }
}

我想做的是监视在 User.ts 的构造函数上调用的 uuid() 方法。我试过这样的事情:

import { User } from './User';

describe('User', () => {
  it('should call uuid() when no id is provided', () => {
    const sut = new User('Foo', 'foo@bar.com', '12345');
    const spy = jest.spyOn(sut, 'uuid');
    expect(spy).toHaveBeenCalledTimes(1);
  });
});

但是没有用。有人知道我该怎么做吗?

您不需要在 uuid 上模拟或安装间谍来测试实现细节。您可以使用 Using a regular expression 进行测试,以检查 user.id 是否为 UUID v4。

使用正则表达式:

If you want to perform the verification on your own using a regular expression, use the regex property, and access its v4 or v5 property

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', 'foo@bar.com', '12345');
    expect(regex.v4.test(user.id!)).toBeTruthy();
  });
});
 PASS  Whosebug/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 test case