【发布时间】: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