NestJS Jest 监听回调函数

发布于 2025-01-09 15:53:02 字数 1559 浏览 1 评论 0原文

所以我有一个具有功能的类。在这个函数中,我从具有回调函数的库的类对象中执行另一个函数。在该回调函数内,有一个我需要监视的方法。有什么办法可以做到这一点吗?这是粗略的细节:

export class Consume {
  private readonly consumer: Consumer; // class from the library
  private readonly randomService: RandomService; // class that it's method I want to spy on

  constructor() {
    this.consumer = new Consumer();
    this.randomService = new RandomService();
  }

  consume(): void {
    this.consumer.consume(async data => {
      ...
      this.randomService.doSomething('withParam'); // I need to spy here on this method
      ...
    })
  }
}

我尝试过嘲笑,但似乎不起作用,这就是我尝试过的:

it('should do something', () => {
  const consumerSpy = jest.spyOn(consumer, 'consume');
  consumerSpy.mockImplementation(cb => {
    cb(['data1', 'data2'])
  }); // mocking the library's function
  const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
  expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
});

还有:

it('should do something', () => {
  jest.mock('path/to/consume-class', () => {
    consume: jest.fn()
  }); // mocking Consume's consume function

  consume.consume(); // calling consume function from Consume class above

  const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
  expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
});

任何帮助将不胜感激! :)

So I have a class which has a function. Inside this function, I execute another function from a library's class object which has a callback function. Inside that callback function, there's a method that I need to spy into. Is there any way to do that? Here's the rough detail:

export class Consume {
  private readonly consumer: Consumer; // class from the library
  private readonly randomService: RandomService; // class that it's method I want to spy on

  constructor() {
    this.consumer = new Consumer();
    this.randomService = new RandomService();
  }

  consume(): void {
    this.consumer.consume(async data => {
      ...
      this.randomService.doSomething('withParam'); // I need to spy here on this method
      ...
    })
  }
}

I've tried mocking, but don't seem to work, here's what I have tried:

it('should do something', () => {
  const consumerSpy = jest.spyOn(consumer, 'consume');
  consumerSpy.mockImplementation(cb => {
    cb(['data1', 'data2'])
  }); // mocking the library's function
  const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
  expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
});

and also this:

it('should do something', () => {
  jest.mock('path/to/consume-class', () => {
    consume: jest.fn()
  }); // mocking Consume's consume function

  consume.consume(); // calling consume function from Consume class above

  const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
  expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
});

Any help would be appreciated! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

愿与i 2025-01-16 15:53:02

您可以通过 jest.spyOn()Class.prototype.method 上安装间谍。

例如

consume.ts:

import { Consumer } from './lib';
import { RandomService } from './random.service';

export class Consume {
  private readonly consumer: Consumer;
  private readonly randomService: RandomService;

  constructor() {
    this.consumer = new Consumer();
    this.randomService = new RandomService();
  }

  consume(): void {
    this.consumer.consume(async (data) => {
      this.randomService.doSomething('withParam');
    });
  }
}

lib.ts:

export class Consumer {
  consume(fn) {
    fn();
  }
}

random.service.ts:

export class RandomService {
  doSomething(param) {}
}

consume.test.ts:

import { Consume } from './consume';
import { Consumer } from './lib';
import { RandomService } from './random.service';

describe('71246273', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('should pass', () => {
    jest.spyOn(Consumer.prototype, 'consume').mockImplementation((fn) => fn());
    const doSomethingSpy = jest.spyOn(RandomService.prototype, 'doSomething');
    const consume = new Consume();
    consume.consume();
    expect(doSomethingSpy).toBeCalledWith('withParam');
  });
});

测试结果:

 PASS  stackoverflow/71246273/consume.test.ts (8.765 s)
  71246273
    ✓ should pass (3 ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   90.91 |      100 |   83.33 |      90 |                   
 consume.ts        |     100 |      100 |     100 |     100 |                   
 lib.ts            |      50 |      100 |       0 |      50 | 3                 
 random.service.ts |     100 |      100 |     100 |     100 |                   
-------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.879 s

You can use install spy on Class.prototype.method via jest.spyOn().

E.g.

consume.ts:

import { Consumer } from './lib';
import { RandomService } from './random.service';

export class Consume {
  private readonly consumer: Consumer;
  private readonly randomService: RandomService;

  constructor() {
    this.consumer = new Consumer();
    this.randomService = new RandomService();
  }

  consume(): void {
    this.consumer.consume(async (data) => {
      this.randomService.doSomething('withParam');
    });
  }
}

lib.ts:

export class Consumer {
  consume(fn) {
    fn();
  }
}

random.service.ts:

export class RandomService {
  doSomething(param) {}
}

consume.test.ts:

import { Consume } from './consume';
import { Consumer } from './lib';
import { RandomService } from './random.service';

describe('71246273', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('should pass', () => {
    jest.spyOn(Consumer.prototype, 'consume').mockImplementation((fn) => fn());
    const doSomethingSpy = jest.spyOn(RandomService.prototype, 'doSomething');
    const consume = new Consume();
    consume.consume();
    expect(doSomethingSpy).toBeCalledWith('withParam');
  });
});

Test result:

 PASS  stackoverflow/71246273/consume.test.ts (8.765 s)
  71246273
    ✓ should pass (3 ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   90.91 |      100 |   83.33 |      90 |                   
 consume.ts        |     100 |      100 |     100 |     100 |                   
 lib.ts            |      50 |      100 |       0 |      50 | 3                 
 random.service.ts |     100 |      100 |     100 |     100 |                   
-------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.879 s
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文