sbatson5 / firestore-jest-mock

Jest Helper library for mocking Cloud Firestore
https://www.npmjs.com/package/firestore-jest-mock
177 stars 57 forks source link

Mock the unsubscribe callback returned by onSnapshot #190

Closed shaoshiva closed 6 months ago

shaoshiva commented 6 months ago

Description

Mock the unsubscribe callback returned by onSnapshot and export the mock as mockQueryOnSnapshotUnsubscribe.

A typical usage is to test whether the unsubscribe callback is called during your application's lifecycle.

Usage

For example, here is a React component that subscribes on mount and unsubscribes on unmount:

const MyComponent = () => {
    useEffect(() => {
        const unsubscribe = firestore().collection('test').onSnapshot(() => {
            console.log('Got a snapshot');
        });

        return () => {
            unsubscribe();
        };
    }, []);

    return (...);
}

We want to test that the component unsubscribes on unmount. Thanks to mockQueryOnSnapshotUnsubscribe we can achieve this like this:

import { mockQueryOnSnapshotUnsubscribe } from 'firestore-jest-mock/mocks/firestore';

describe('MyComponent', () => {
    it('should unsubscribe on umount', () => {
        const { unmount } = render(<MyComponent />);
        expect(mockQueryOnSnapshotUnsubscribe).toHaveBeenCalledTimes(0);
        unmount();
        expect(mockQueryOnSnapshotUnsubscribe).toHaveBeenCalledTimes(1);
    });
});

Related issues

Addresses #189

How to test

Unit tests full-setup-library-firestore.test.js and full-setup.test.js have been updated in order to assert that the unsubscribe callback returned by onSnapshot is mockQueryOnSnapshotUnsubscribe.

sbatson5 commented 6 months ago

Merged and released in version 0.25.0. Thanks!

shaoshiva commented 6 months ago

Awesome, thank you @sbatson5 for you reactivity 🙏