I am writing a unit test for a pubsub component in my service. My directory structure looks like this:
src
|
|-- common
| |
| |-- pubsub
| |
| |-- publish_to_topic.ts
|-- publishers
|
|-- publish_event.ts
tests
|
|-- publishers
|
|-- publish_event.test.ts
The file publish_to_topic.ts
looks like this
export default async publishToTopic<T>(
pubSubClient,
topic,
data) {
...
}
And is called by publish_event.ts
like so:
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 });
}
Lastly in my test file publish_event.test.ts
, I set up a mock:
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();
});
})
Alas, my test fails:
Expected number of calls: >= 1
Received number of calls: 0
Can anyone explain where I've gone wrong? Thank you.
CodePudding user response:
You have your mocked function wrapped in a second function (without calling the mock itself).
Update to this:
beforeEach(() => {
mockPublishToTopic = jest.fn();
jest.mock('./../../src/common/pubsub/publish_to_topic', mockPublishToTopic);
});