Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock the unsubscribe callback returned by onSnapshot #190

Merged

Conversation

shaoshiva
Copy link
Contributor

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 sbatson5 merged commit 8dc4295 into sbatson5:master Apr 12, 2024
4 checks passed
@sbatson5
Copy link
Owner

Merged and released in version 0.25.0. Thanks!

@shaoshiva
Copy link
Contributor Author

Awesome, thank you @sbatson5 for you reactivity 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants