From 24fee29f7a8ab328bb35e66d145d6b9c2d018c1d Mon Sep 17 00:00:00 2001 From: Kudo Chien Date: Thu, 28 Nov 2024 05:05:31 -0800 Subject: [PATCH] Add useColorScheme mock test (#47988) Summary: add a jest test to test when `useColorScheme` is not mocked. following up https://github.com/facebook/react-native/pull/47629#issuecomment-2491534678 ## Changelog: [GENERAL] [ADDED] - Add useColorScheme mock test Pull Request resolved: https://github.com/facebook/react-native/pull/47988 Test Plan: ci passed Reviewed By: javache Differential Revision: D66573172 Pulled By: blakef fbshipit-source-id: 820227f6fc4e18a968b3181fad8f534a716f1e9e --- .../__tests__/useColorScheme-test.js | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 packages/react-native/Libraries/Utilities/__tests__/useColorScheme-test.js diff --git a/packages/react-native/Libraries/Utilities/__tests__/useColorScheme-test.js b/packages/react-native/Libraries/Utilities/__tests__/useColorScheme-test.js new file mode 100644 index 00000000000..1ba2463968e --- /dev/null +++ b/packages/react-native/Libraries/Utilities/__tests__/useColorScheme-test.js @@ -0,0 +1,39 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import useColorScheme from '../useColorScheme'; + +describe('useColorScheme', () => { + it('should return a mocked light theme by default', () => { + expect(jest.isMockFunction(useColorScheme)).toBe(true); + expect(useColorScheme()).toBe('light'); + }); + + it('should have console.error when not using mock', () => { + const useColorSchemeActual = jest.requireActual<{ + default: typeof useColorScheme, + }>('../useColorScheme').default; + const spy = jest.spyOn(console, 'error').mockImplementationOnce(() => { + // Simulate LogBox console.error() call to throw an error and stop the further execution + throw new Error('console.error() was called'); + }); + + expect(() => { + useColorSchemeActual(); + }).toThrow(); + + expect(spy).toHaveBeenCalledWith( + expect.stringMatching( + /Invalid hook call. Hooks can only be called inside of the body of a function component./, + ), + ); + }); +});