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

feat: Add @testing-library/react-native #5197

Merged
merged 16 commits into from
Aug 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ module.exports = {
testMatch: ["<rootDir>/src/**/__tests__/*tests.(ts|tsx|js)", "<rootDir>/scripts/**/*tests.(ts|tsx|js)", "<rootDir>/__tests__/**/*tests.(ts|tsx|js)"],
testEnvironment: "jsdom",
testURL: "http://localhost/",
setupFilesAfterEnv: ["./src/setupJest.ts"],
setupFilesAfterEnv: ["./src/setupJest.ts", "@testing-library/jest-native/extend-expect"],
cacheDirectory: ".jest/cache",
transform: {
"^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$":
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@
"@storybook/addon-actions": "^5.3",
"@storybook/react-native": "^5.3.25",
"@storybook/react-native-server": "^5.3.23",
"@testing-library/jest-native": "^4.0.1",
"@testing-library/react-native": "7.1.0",
"@types/argparse": "^2.0.8",
"@types/chalk": "2.2.0",
"@types/dedent": "0.7.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

import { BidderPositionQueryResponse } from "__generated__/BidderPositionQuery.graphql"
import { ConfirmBid_sale_artwork } from "__generated__/ConfirmBid_sale_artwork.graphql"
import { ConfirmBidCreateBidderPositionMutationResponse } from "__generated__/ConfirmBidCreateBidderPositionMutation.graphql"
Expand Down
45 changes: 18 additions & 27 deletions src/lib/Components/__tests__/ArtsyReactWebView-tests.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { waitFor } from "@testing-library/react-native"
import mockFetch from "jest-fetch-mock"
import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader"
import { goBack, navigate } from "lib/navigation/navigate"
Expand Down Expand Up @@ -40,7 +41,7 @@ describe(ArtsyReactWebViewPage, () => {
it("shares the correct URL", () => {
const tree = render({ showShareButton: true })
tree.root.findByType(FancyModalHeader).props.onRightButtonPress()
setTimeout(() => expect(jest.fn()).toHaveBeenCalledWith())
waitFor(() => expect(jest.fn()).toHaveBeenCalledTimes(1))
})
it("calls goBack when the close/back button is pressed", () => {
const tree = render()
Expand Down Expand Up @@ -164,12 +165,6 @@ describe(ArtsyReactWebViewPage, () => {
})

describe(useWebViewCookies, () => {
beforeAll(() => {
jest.useFakeTimers()
})
afterAll(() => {
jest.useRealTimers()
})
beforeEach(() => {
mockFetch.mockClear()
})
Expand All @@ -182,46 +177,42 @@ describe(useWebViewCookies, () => {
act(() => {
renderWithWrappers(<Wrapper />)
})
expect(mockFetch).toHaveBeenCalledWith("https://staging.artsy.net", {
method: "HEAD",
headers: { "X-Access-Token": "userAccessToken" },
})
expect(mockFetch).toHaveBeenCalledWith("https://live-staging.artsy.net/login", {
method: "HEAD",
headers: { "X-Access-Token": "userAccessToken" },
waitFor(() => {
expect(mockFetch).toHaveBeenCalledWith("https://staging.artsy.net", {
method: "HEAD",
headers: { "X-Access-Token": "userAccessToken" },
})
expect(mockFetch).toHaveBeenCalledWith("https://live-staging.artsy.net/login", {
method: "HEAD",
headers: { "X-Access-Token": "userAccessToken" },
})
})
})
it("retries if it fails", async () => {
__globalStoreTestUtils__?.injectState({ native: { sessionState: { authenticationToken: "userAccessToken" } } })
mockFetch.mockReturnValue(Promise.resolve({ ok: false, status: 500 } as any))
const tree = renderWithWrappers(<Wrapper />)
await act(() => undefined)
expect(mockFetch).toHaveBeenCalledTimes(2)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(2))

jest.runOnlyPendingTimers()
expect(mockFetch).toHaveBeenCalledTimes(4)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(4))

await act(() => undefined)
jest.runOnlyPendingTimers()
expect(mockFetch).toHaveBeenCalledTimes(6)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(6))

await act(() => undefined)
jest.runOnlyPendingTimers()
expect(mockFetch).toHaveBeenCalledTimes(8)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(8))

await act(() => undefined)
jest.runOnlyPendingTimers()
expect(mockFetch).toHaveBeenCalledTimes(10)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(10))

tree.unmount()

await act(() => undefined)
jest.runOnlyPendingTimers()
expect(mockFetch).toHaveBeenCalledTimes(10)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(10))

await act(() => undefined)
jest.runOnlyPendingTimers()
expect(mockFetch).toHaveBeenCalledTimes(10)
waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(10))
})
})

Expand Down
4 changes: 0 additions & 4 deletions src/lib/Scenes/Home/__tests__/Home-tests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ jest.mock("lib/Scenes/Home/Components/SalesRail", () => ({
SalesRailFragmentContainer: jest.fn(() => null),
}))

jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

import { EmailConfirmationBanner } from "lib/Scenes/Home/Components/EmailConfirmationBanner"
import { SalesRailFragmentContainer } from "lib/Scenes/Home/Components/SalesRail"
import { GlobalStoreProvider } from "lib/store/GlobalStore"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { waitFor } from "@testing-library/react-native"
import { ComposerTestsQuery } from "__generated__/ComposerTestsQuery.graphql"
import { __globalStoreTestUtils__ } from "lib/store/GlobalStore"
import { extractText } from "lib/tests/extractText"
Expand Down Expand Up @@ -135,9 +136,7 @@ describe("inquiry offer enabled", () => {

input.props.onFocus()

setTimeout(() => {
expect(tree.root.findAllByType(CTAPopUp)[0]).not.toBeDefined()
}, 0)
waitFor(() => expect(tree.root.findAllByType(CTAPopUp)[0]).not.toBeDefined())
})

describe("with associated orders (OrderCTAs)", () => {
Expand Down
4 changes: 0 additions & 4 deletions src/lib/Scenes/MyProfile/__tests__/LoggedInUserInfo-tests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ import { act } from "react-test-renderer"
import { createMockEnvironment } from "relay-test-utils"
import { UserProfileQueryRenderer } from "../LoggedInUserInfo"

jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

jest.unmock("react-relay")
const env = (defaultEnvironment as any) as ReturnType<typeof createMockEnvironment>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ import {
PushAuthorizationStatus,
} from "../MyProfilePushNotifications"

jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

const mockFetchNotificationPermissions = LegacyNativeModules.ARTemporaryAPIModule
.fetchNotificationPermissions as jest.Mock<any>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Checkbox } from "lib/Components/Bidding/Components/Checkbox"
import { fetchMockResponseOnce } from "lib/tests/fetchMockHelpers"
import { renderWithWrappers } from "lib/tests/renderWithWrappers"
import React from "react"
import { __globalStoreTestUtils__ } from "../../../../store/GlobalStore"
Expand All @@ -13,25 +14,7 @@ const navigationMock = {
replace: replaceMock,
}

const mockFetch = jest.fn()

;(global as any).fetch = mockFetch

function mockFetchResponseOnce(response: Partial<Response>) {
mockFetch.mockResolvedValueOnce(response)
}
function mockFetchJsonOnce(json: object, status: number = 200) {
mockFetch.mockResolvedValueOnce({
status,
json: () => Promise.resolve(json),
})
}

describe("OnboardingCreateAccount", () => {
beforeEach(() => {
mockFetch.mockClear()
})

it("form validation works properly", async () => {
const tree = renderWithWrappers(<OnboardingCreateAccount navigation={navigationMock as any} route={null as any} />)

Expand All @@ -56,12 +39,17 @@ describe("OnboardingCreateAccount", () => {
expect(signUpButton.props.disabled).toEqual(false)
expect(signUpButton.props.error).toEqual(undefined)

mockFetchJsonOnce({
xapp_token: "my-special-token",
expires_in: "never",
fetchMockResponseOnce(
JSON.stringify({
xapp_token: "my-special-token",
expires_in: "never",
})
)

fetchMockResponseOnce({
status: 404,
})

mockFetchResponseOnce({ status: 404 })
signUpButton.props.onPress()

await flushPromiseQueue()
Expand Down Expand Up @@ -92,21 +80,25 @@ describe("OnboardingCreateAccount", () => {

expect(signUpButton.props.disabled).toEqual(false)

mockFetchResponseOnce({ status: 201 })
mockFetchJsonOnce({
xapp_token: "my-special-token",
expires_in: "never",
})
mockFetchJsonOnce(
{
fetchMockResponseOnce({ status: 201 })
fetchMockResponseOnce(
JSON.stringify({
xapp_token: "my-special-token",
expires_in: "never",
})
)
fetchMockResponseOnce(
JSON.stringify({
access_token: "my-access-token",
expires_in: "a billion years",
},
201
status: 201,
})
)
fetchMockResponseOnce(
JSON.stringify({
id: "my-user-id",
})
)
mockFetchJsonOnce({
id: "my-user-id",
})
const isLoggedIn = !!__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken
expect(isLoggedIn).toEqual(false)

Expand All @@ -126,12 +118,14 @@ describe("OnboardingCreateAccount", () => {

emailInput.props.onChangeText("[email protected]")

mockFetchJsonOnce({
xapp_token: "my-special-token",
expires_in: "never",
})
fetchMockResponseOnce(
JSON.stringify({
xapp_token: "my-special-token",
expires_in: "never",
})
)

mockFetchResponseOnce({ status: 200 })
fetchMockResponseOnce({ status: 200 })
signUpButton.props.onPress()

setTimeout(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { OrderDetailsTestsQuery } from "__generated__/OrderDetailsTestsQuery.graphql"
import { PageWithSimpleHeader } from "lib/Components/PageWithSimpleHeader"
import { extractText } from "lib/tests/extractText"
import { mockEnvironmentPayload } from "lib/tests/mockEnvironmentPayload"
import { renderWithWrappers } from "lib/tests/renderWithWrappers"
Expand Down Expand Up @@ -123,8 +122,4 @@ describe(OrderDetailsQueryRender, () => {
const tree = renderWithWrappers(<OrderDetailsQueryRender orderID="21856921-fa90-4a36-a17e-dd52870952d2" />)
expect(tree.root.findAllByType(OrderDetailsPlaceholder)).toHaveLength(1)
})
it("Loads OrderHistoryQueryRender with PageWithSimpleHeader", () => {
const tree = renderWithWrappers(<OrderDetailsQueryRender orderID="21856921-fa90-4a36-a17e-dd52870952d2" />)
expect(tree.root.findAllByType(PageWithSimpleHeader)).toHaveLength(1)
})
Comment on lines -126 to -129
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For clarification, this test is removed because it tests the exact same thing as the test above.

})
4 changes: 0 additions & 4 deletions src/lib/Scenes/OrderHistory/__tests__/OrderHistory-tests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ import { OrderHistoryPlaceholder } from "../OrderHistory"
import { OrderHistoryRowContainer } from "../OrderHistoryRow"
jest.unmock("react-relay")

jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

describe(OrderHistoryQueryRender, () => {
it("Loads OrderHistoryQueryRender", () => {
const tree = renderWithWrappers(<OrderHistoryQueryRender />)
Expand Down
30 changes: 17 additions & 13 deletions src/lib/Scenes/Sale/__tests__/Sale-tests.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { waitFor } from "@testing-library/react-native"
import { navigate, popParentViewController } from "lib/navigation/navigate"
import { __globalStoreTestUtils__ } from "lib/store/GlobalStore"
import { renderWithWrappers } from "lib/tests/renderWithWrappers"
Expand Down Expand Up @@ -32,12 +33,10 @@ describe("Sale", () => {

beforeEach(() => {
mockEnvironment = createMockEnvironment()
jest.useFakeTimers()
})

afterEach(() => {
jest.clearAllMocks()
jest.useRealTimers()
})

it("switches to live auction view when sale goes live", () => {
Expand All @@ -60,10 +59,11 @@ describe("Sale", () => {
)

expect(navigate).toHaveBeenCalledTimes(0)
jest.advanceTimersByTime(1000)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

expect(navigate).toHaveBeenCalledTimes(1)
expect(navigate).toHaveBeenCalledWith("https://live-staging.artsy.net/live-sale-slug")
expect(popParentViewController).toHaveBeenCalledTimes(1)
waitFor(() => {
expect(navigate).toHaveBeenCalledTimes(1)
expect(navigate).toHaveBeenCalledWith("https://live-staging.artsy.net/live-sale-slug")
expect(popParentViewController).toHaveBeenCalledTimes(1)
})
})

it("switches to live auction view when sale goes live with no endAt", () => {
Expand All @@ -87,10 +87,12 @@ describe("Sale", () => {
)

expect(navigate).toHaveBeenCalledTimes(0)
jest.advanceTimersByTime(1000)
expect(navigate).toHaveBeenCalledTimes(1)
expect(navigate).toHaveBeenCalledWith("https://live-staging.artsy.net/live-sale-slug")
expect(popParentViewController).toHaveBeenCalledTimes(1)

waitFor(() => {
expect(navigate).toHaveBeenCalledTimes(1)
expect(navigate).toHaveBeenCalledWith("https://live-staging.artsy.net/live-sale-slug")
expect(popParentViewController).toHaveBeenCalledTimes(1)
})
})

it("doesn't switch to live auction view when sale is closed", () => {
Expand All @@ -110,9 +112,11 @@ describe("Sale", () => {
)

expect(navigate).toHaveBeenCalledTimes(0)
jest.advanceTimersByTime(1000)
expect(navigate).toHaveBeenCalledTimes(0)
expect(popParentViewController).toHaveBeenCalledTimes(0)

waitFor(() => {
expect(navigate).toHaveBeenCalledTimes(0)
expect(popParentViewController).toHaveBeenCalledTimes(0)
})
})

it("renders a Register button when registrations are open", () => {
Expand Down
4 changes: 0 additions & 4 deletions src/lib/Scenes/Search/__tests__/AutosuggestResults-tests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,6 @@ const TestWrapper: typeof AutosuggestResults = (props) => (
</SearchContext.Provider>
)

jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

jest.mock("lodash", () => ({
...jest.requireActual("lodash"),
throttle: (f: any) => f,
Expand Down
4 changes: 0 additions & 4 deletions src/lib/Scenes/VanityURL/__tests__/VanityURLEntity-tests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils"
import { VanityURLEntityRenderer } from "../VanityURLEntity"
import { VanityURLPossibleRedirect } from "../VanityURLPossibleRedirect"

jest.mock("lib/relay/createEnvironment", () => ({
defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

jest.unmock("react-relay")

jest.mock("../VanityURLPossibleRedirect", () => {
Expand Down
Loading