Search code examples
javascriptreact-nativeunit-testingjestjs

Props data appears undefined when trying to render screen for testing


I'm doing jest testing for my react-native app and I want to test that my Game Screen renders correctly. I wrote the following test below to pass the required params to the Game Screen.

  it("renders correctly", () => {
    const mockedParams = {
      route: { params: { words: ["superior", "baikal"], stage: 0 } },
      navigation: ''
    };

    const gameScreen = renderer.create(<GameScreen {...mockedParams} />).toJSON();

    expect(gameScreen).toBeTruthy();
  });

Game Screen

const Game = ({ route, navigation }) => {
  const {words, stage} = route.params;
  const [lives, setLives] = useState(3);
  const [points, setPoints] = useState(0);
  const [level, setLevel] = useState(0);
  const [letters, setLetters] = useState(words[level].word.split(""));
  const [curLetter, setCurLetter] = useState(0);
  const [showPopup, setShowPopup] = useState(false);
  const [rows, setRows] = useState(
    new Array(1).fill(new Array(letters.length).fill(""))
  );

However when I run the test, I get the following error:

TypeError: Cannot read property 'split' of undefined

It seems like the words prop is undefined when it gets passed to the Game Screen even though I have defined values for it in my test file. How do I fix this?


Solution

  • Params: { words: ["superior", "baikal"], ...}

    You're using: words[level].word.split("")

    So you don't have a words[level].word.

    You can tell that params are defined because it gets to word instead of words before there's an error. You could confirm this by logging out your params at the top of your component, but that part looks fine.

    Your component is expecting something like { words: [{ word: "superior" }, ...}, so either pass it that way, or access the current params with words[level].split.