简体   繁体   English

如何使用 Jest 和 Typescript 监视不属于正在测试的 class 的 function

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

I'm trying to spy on a function that come from uuidv4 package but I didn't figure out how to do that.我正在尝试监视来自 uuidv4 package 的 function,但我不知道该怎么做。

This is my User Class:这是我的用户 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.我想做的是监视在 User.ts 的构造函数上调用的 uuid() 方法。 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', 'foo@bar.com', '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 uuid to test the implementation detail.您不需要在uuid上模拟或安装 spy 来测试实现细节。 You can test the with Using a regular expression to check user.id is a UUID v4 or not.您可以使用正则表达式来测试user.id是否为 UUID v4。

Using a regular expression:使用正则表达式:

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如果您想使用正则表达式自行执行验证,请使用 regex 属性,并访问其 v4 或 v5 属性

index.ts : 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 : 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  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

Also take a look at the uuid test case另请查看uuid 测试用例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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