Created
July 16, 2020 20:55
-
-
Save jrapala/343e7a83fb1738dc15163ea50535692f to your computer and use it in GitHub Desktop.
Mocking RN Linking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import { Linking } from "react-native" | |
import { cleanup, fireEvent } from "react-native-testing-library" | |
import { renderWithTheme } from "testHelpers/componentWrappers" | |
import ExternalLink from "./" | |
const externalLinkTestId = "external-link" | |
jest.mock("react-native/Libraries/Linking/Linking", () => ({ | |
openURL: jest.fn(() => Promise.resolve("mockResolve")), | |
})) | |
describe("[External Link]", () => { | |
let componentRender | |
beforeEach(() => { | |
componentRender = () => renderWithTheme( | |
<ExternalLink | |
testID={externalLinkTestId} | |
uri="mockURI" | |
> | |
test link | |
</ExternalLink> | |
) | |
}) | |
afterEach(cleanup) | |
it("displays the external link", () => { | |
const { queryByTestId } = componentRender() | |
expect(queryByTestId(externalLinkTestId)).not.toBeNull() | |
}) | |
it("handles onPress as expected", () => { | |
const { queryByTestId } = componentRender() | |
fireEvent.press(queryByTestId(externalLinkTestId)) | |
expect(Linking.openURL).toHaveBeenCalledTimes(1) | |
}) | |
it("logs promise catch error", () => { | |
Linking.openURL = jest.fn(() => Promise.reject("mockError")) | |
const { queryByTestId } = componentRender() | |
fireEvent.press(queryByTestId(externalLinkTestId)) | |
expect(Linking.openURL).toHaveBeenCalledTimes(1) | |
}) | |
it("handles disabled styles", () => { | |
componentRender = () => renderWithTheme( | |
<ExternalLink | |
disabled | |
testID={externalLinkTestId} | |
uri="mockURI" | |
> | |
test link | |
</ExternalLink> | |
) | |
const { queryByTestId } = componentRender() | |
expect(queryByTestId(externalLinkTestId)).not.toBeNull() | |
}) | |
}) |
Good method, but I have to also mock event listener functions to make it work.
jest.mock('react-native/Libraries/Linking/Linking', () => ({
openURL: jest.fn().mockResolvedValue(null),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
}));
needed an example of mocking openURL in a pinch and this did the trick. Thank you!
@Coffeegerm yes, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@anabeatrizzz the second parameter for jest.mock is a module factory that returns back the mocked methods of the module, for this instance we are returning back a mocked implementation for the openURL method that Linking exports. If you don't mock the module and attempt to do any sort of verification of the module being called you will receive an error from jest due to the function not being a mocked one. Does that help?