【问题标题】:Mocking an instance within a class在类中模拟实例
【发布时间】:2021-11-19 20:38:19
【问题描述】:

晚上好,

我正在尝试为以下打字稿类创建一些测试。我正在尝试创建一个测试,以便我可以验证内部 BroadcastChannel 是否已调用其 postMessage 方法,但我无法创建相关的间谍来执行此操作。我猜这是因为我没有将间谍附加到类中的实际实例,但我不确定。

export class BroadcastChannelService<T> {
  private readonly broadcastChannel: BroadcastChannel;

  constructor(name: CHANNEL_NAMES) {
    this.broadcastChannel = new BroadcastChannel(name);
  }

  postMessage = (msg: T) => {
    this.broadcastChannel.postMessage(msg);
  }
}

以下是我目前的测试

import { BroadcastChannel } from 'broadcast-channel';

import { BroadcastChannelService } from '../../services';

jest.mock('broadcast-channel');
const mockedBroadcastChannel = BroadcastChannel as jest.Mocked<typeof BroadcastChannel>;

describe('BroadcastChannelService', () => {
  let subject: BroadcastChannelService<string>;

  describe('constructor', () => {
    afterAll(() => {
      jest.resetAllMocks();
    });

    test('is successful', () => {
      // eslint-disable-next-line no-unused-vars
      subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
      expect(mockedBroadcastChannel).toBeCalledWith('GOOGLE_AUTH');
      expect(mockedBroadcastChannel).toBeCalledTimes(1);
    });
  });

  describe('postMessage', () => {
    beforeAll(() => {
      subject = new BroadcastChannelService('GOOGLE_AUTH');
      subject.postMessage('Hello World');
    });

    afterAll(() => {
      jest.resetAllMocks();
    });

    test('is successful', () => {
    });
  });
});

【问题讨论】:

    标签: typescript jestjs mocking


    【解决方案1】:

    所以诀窍是使用spyOn 和mockedBroadcastChannel.prototype

    import { BroadcastChannel } from 'broadcast-channel';
    import { BroadcastChannelService } from '../../services';
    
    jest.mock('broadcast-channel');
    const mockedBroadcastChannel = BroadcastChannel as jest.Mocked<typeof BroadcastChannel>;
    
    describe('BroadcastChannelService', () => {
      let subject: BroadcastChannelService<string>;
    
      describe('constructor', () => {
        test('is successful', () => {
          // eslint-disable-next-line no-unused-vars
          subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
          expect(mockedBroadcastChannel).toBeCalledWith('GOOGLE_AUTH');
          expect(mockedBroadcastChannel).toBeCalledTimes(1);
        });
      });
    
      describe('postMessage', () => {
        test('is successful', () => {
          const postMessageSpy = jest.spyOn(mockedBroadcastChannel.prototype, 'postMessage');
          subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
          subject.postMessage('Hello World');
          expect(postMessageSpy).toBeCalledTimes(1);
          expect(postMessageSpy).toBeCalledWith('Hello World');
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2019-03-22
      • 2013-07-17
      • 2019-07-27
      • 2018-07-30
      • 2020-07-13
      相关资源
      最近更新 更多