0

I'm trying to implement test for my component that adapt to the light/dark mode using react-native-appearance.

As the most of my others component use this Text component, i've mocked the module globally using setupFiles :

import * as mocking from "react-native-appearance/src/mock";

jest.mock('react-native-appearance', () => mocking);

But would like to test, only for my Text component the dark mode so i tried something like :

const props: Props = {children: "Test", primary: true};

jest.unmock('react-native-appearance')

const mock = jest.fn();

jest.mock('react-native-appearance', () => ({
    useColorScheme: mock
}))

describe('<Text>', () => {
    describe('Themes', () => {
        it('Renders correctly in light theme', () => {
            const tree = create(<Text {...props}/>)

            expect(tree.toJSON()).toMatchSnapshot();
        })

        it('Renders correctly in dark theme', () => {
            mock.mockReturnValue('dark');
            const tree = create(<Text {...props}/>)

            expect(tree.toJSON()).toMatchSnapshot();
        })
    });
})

But this error occured :

TypeError: (0 , _reactNativeAppearance.useColorScheme) is not a function

Is something i'm doing wrong ? Note that i'm using typescript.

Toto NaBendo
  • 290
  • 3
  • 26

1 Answers1

2

Jest automatically hoists the import methods to the top of the file. This is what ensures that the mocks will override the default imports. https://jestjs.io/docs/en/manual-mocks#using-with-es-module-imports

This means that your mocked module will not have access to the mock variable.

What you could do instead here is to mock the module, import the mocked function, and run your assertions against that imported module.

import { useColorScheme } from "react-native-appearance";

jest.mock("react-native-appearance", () => ({
  useColorScheme: jest.fn(),
}));

describe("test", () => {
  it("renders correctly", () => {
    useColorScheme.mockReturnValueOnce('dark');

    renderer.create(<App />);

    expect(useColorScheme).toHaveBeenCalledTimes(1);
  });
});
nipuna-g
  • 6,252
  • 3
  • 31
  • 48
  • Right, but to mock the return value with `.mockReturnValueOnce('dark')` of the module, I need to access that jest.fn() function – Toto NaBendo Feb 24 '21 at 14:16
  • You can set either `mockReturnValueOnce` or `mockImplementation` on the mocked function so that it returns the value you want. Just updated the answer to include this. – nipuna-g Feb 24 '21 at 14:23