繁体   English   中英

JavaScript/Node - 为什么我的笑话没有被调用?

[英]JavaScript/Node - Why isn't my jest mock being called?

我正在为我的服务中的 pubsub 组件编写单元测试。 我的目录结构如下所示:

src
|
|-- common
|    |
|    |-- pubsub
|        |
|        |-- publish_to_topic.ts
|-- publishers
    |
    |-- publish_event.ts

tests
|
|-- publishers
    |
    |-- publish_event.test.ts

文件publish_to_topic.ts看起来像这样

export default async publishToTopic<T>(
    pubSubClient,
    topic,
    data) {
    ...
}

并由publish_event.ts调用,如下所示:

import { pubSub } from './../common/pubsub_client';
import publishToTopic from './../common/pubsub/publish_to_topic';

export async function publishEvent(
   event,
   time,
   metadata = {}) {
  return publishToTopic(
    pubSub,
    'my-topic',
    { data: event, timestamp: time, metadata });
}

最后在我的测试文件publish_event.test.ts中,我设置了一个模拟:

import { publishEvent } from './../../src/publishers/avoidance_area_change_event';

describe("test publisher", () => {
  let mockPublishToTopic;

  beforeEach(() => {
    mockPublishToTopic = jest.fn();
    jest.mock('./../../src/common/pubsub/publish_to_topic', () => mockPublishToTopic);
  });

  it("test1", async () => {
    const data = ...;
    const time = new Date();
    const metadata = {};

    publishEvent(event, time, metadata);

    expect(mockPublishToTopic).toBeCalled();
  });
})

唉,我的测试失败了:

Expected number of calls: >= 1
Received number of calls:    0

谁能解释我哪里出错了? 谢谢你。

您将模拟的 function 包裹在第二个 function 中(不调用模拟本身)。

对此进行更新:

beforeEach(() => {
    mockPublishToTopic = jest.fn();
    jest.mock('./../../src/common/pubsub/publish_to_topic', mockPublishToTopic);
  });

暂无
暂无

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

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