简体   繁体   中英

Using custom mocks for components with jest

I'm writing a React-Native application in which I have a screen I need to test:

MyScreen.js

import React, { Component } from "react";
import CustomTable from "./CustomTable";

export default MyScreen extends Component {
  render() {
    return <CustomTable />;
  }
}

CustomTable.ios.js

import React, { Component } from "react";
import { View } from "react-native";
import TableView from "react-native-tableview";

export default MyScreen extends Component {
  render() {
    return (
      <View>
        ...some stuff
        <TableView />
      </View>
    );
  }
}

react-native-tableview calls some iOS specific code so I have mocked it out by simply returning the android version ( CustomTable.android.js ) in the __mocks__ folder

__mocks__/CustomTable.ios.js

import CustomAndroidTable from "../CustomTable.android";
export const CustomTable = CustomAndroidTable;

What I want to do is test MyScreen.js with Jest, but I want it to use the __mock__/CustomTable.ios . How do I go about getting it to do that? Is that even possible with Jest? My current test file looks like:

tests/MyScreen.test.js

import React from "react";
import renderer from "react-test-renderer";
import MyScreen from "../src/MyScreen";

describe("test", () => {
  it("works", () => {
  jest.mock("../src/CustomTable.ios");
  const tree = renderer.create(
    <MyScreen />,
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

But it still calls the original version of CustomTable.ios . What am i doing wrong?

You should call jest.mock outside of your suite test. It should be immediately after your imports.

import React from "react";
import renderer from "react-test-renderer";
import MyScreen from "../src/MyScreen";

jest.mock("../src/CustomTable.ios");

describe("test", () => {
  it("works", () => {
  const tree = renderer.create(
    <MyScreen />,
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM