Reputation: 73
I'm creating tests in Jest to ensure that a function is working correctly. In my test, I fire off my function and check that the function inside has been called. However, I get the error:
received value must be a mock or spy function.
As far as I'm aware I'm mocking firebase correctly and looking for the correct function. Any help would be hugely appreciated.
This is the function in question, in the notifications.js
file:
export async function subscribeToTopic(topic) {
await firebase.messaging().subscribeToTopic(topic)
}
I've mocked firebase in a setupTest.js
file
import 'react-native-firebase'
jest.mock('react-native-firebase', () => ({
messaging: jest.fn(() => ({
hasPermission: jest.fn(() => Promise.resolve(true)),
subscribeToTopic: jest.fn(),
unsubscribeFromTopic: jest.fn(),
requestPermission: jest.fn(() => Promise.resolve(true)),
getToken: jest.fn(() => Promise.resolve('myMockToken')),
})),
notifications: jest.fn(() => ({
onNotification: jest.fn(),
getInitialNotification: jest.fn(),
})),
}))
And here is my test within notifications.test.js
import { subscribeToTopic } from './notifications'
import firebase from 'react-native-firebase'
describe('notifications', () => {
describe('topics', () => {
const topic = 'topic'
it('should subscribe to a topic', async () => {
subscribeToTopic(topic)
await expect(firebase.messaging().subscribeToTopic).toHaveBeenCalled()
})
})
})
Upvotes: 0
Views: 2207
Reputation: 102267
Here is the solution:
notifications.ts
:
import firebase from 'react-native-firebase';
export async function subscribeToTopic(topic) {
await firebase.messaging().subscribeToTopic(topic);
}
notifications.test.ts
:
import { subscribeToTopic } from './notifications';
import firebase from 'react-native-firebase';
jest.mock('react-native-firebase', () => {
return {
messaging: jest.fn().mockReturnThis(),
subscribeToTopic: jest.fn()
};
});
describe('notifications', () => {
describe('topics', () => {
const topic = 'topic';
it('should subscribe to a topic', async () => {
await subscribeToTopic(topic);
expect(firebase.messaging().subscribeToTopic).toHaveBeenCalled();
});
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/58859904/notifications.spec.ts
notifications
topics
✓ should subscribe to a topic (5ms)
------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
notifications.ts | 100 | 100 | 100 | 100 | |
------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.844s, estimated 10s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58859904
Upvotes: 1