I am writing a unit test for a pubsub component in my service. My directory structure looks like this:
JavaScript
x
17
17
1
src
2
|
3
|-- common
4
| |
5
| |-- pubsub
6
| |
7
| |-- publish_to_topic.ts
8
|-- publishers
9
|
10
|-- publish_event.ts
11
12
tests
13
|
14
|-- publishers
15
|
16
|-- publish_event.test.ts
17
The file publish_to_topic.ts
looks like this
JavaScript
1
7
1
export default async publishToTopic<T>(
2
pubSubClient,
3
topic,
4
data) {
5
6
}
7
And is called by publish_event.ts
like so:
JavaScript
1
13
13
1
import { pubSub } from './../common/pubsub_client';
2
import publishToTopic from './../common/pubsub/publish_to_topic';
3
4
export async function publishEvent(
5
event,
6
time,
7
metadata = {}) {
8
return publishToTopic(
9
pubSub,
10
'my-topic',
11
{ data: event, timestamp: time, metadata });
12
}
13
Lastly in my test file publish_event.test.ts
, I set up a mock:
JavaScript
1
21
21
1
import { publishEvent } from './../../src/publishers/avoidance_area_change_event';
2
3
describe("test publisher", () => {
4
let mockPublishToTopic;
5
6
beforeEach(() => {
7
mockPublishToTopic = jest.fn();
8
jest.mock('./../../src/common/pubsub/publish_to_topic', () => mockPublishToTopic);
9
});
10
11
it("test1", async () => {
12
const data = ;
13
const time = new Date();
14
const metadata = {};
15
16
publishEvent(event, time, metadata);
17
18
expect(mockPublishToTopic).toBeCalled();
19
});
20
})
21
Alas, my test fails:
JavaScript
1
3
1
Expected number of calls: >= 1
2
Received number of calls: 0
3
Can anyone explain where I’ve gone wrong? Thank you.
Advertisement
Answer
You have your mocked function wrapped in a second function (without calling the mock itself).
Update to this:
JavaScript
1
5
1
beforeEach(() => {
2
mockPublishToTopic = jest.fn();
3
jest.mock('./../../src/common/pubsub/publish_to_topic', mockPublishToTopic);
4
});
5