Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6208

Error in jest test: TypeError: Cannot read property 'container' of undefined

$
0
0

I'm trying to test a typescript react-native class using jest but the test is not passing.

This is the class:

import * as React from "react";
import {
  Image,
  KeyboardAvoidingView,
  StyleSheet,
  View
} from "react-native";
import colors from "../config/colors";
import constants from "../config/constants";
import App from "../../App";

interface Props {
  ...
}

interface State {
...
}

class LoginScreen extends React.Component<Props, State> {
 .
 .
 .  
  render() {

    return (
      <KeyboardAvoidingView
        style={styles.container}   
        behavior={constants.IS_IOS ? "padding" : undefined}>
        .
        .
        .
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({  
  container: {
    flex: 1,
    backgroundColor: colors.WHITE,
    alignItems: "center",
    justifyContent: "space-between"
  }
});

export default LoginScreen

but I'm getting the error:

TypeError: Cannot read property 'container' of undefined

       98 |     return (
       99 |       <KeyboardAvoidingView
    > 100 |         style={styles.container}   
          |                       ^
      101 |         behavior={constants.IS_IOS ? "padding" : undefined}>

The test is this one:

/**
 * @format
 */

import 'react-native';
import React from 'react';
import LoginScreen from '../src/screens/LoginScreen';

// Note: test renderer must be required after react-native.
import * as renderer from 'react-test-renderer';

jest.mock('react-native', () => {
  return { 
    StyleSheet: {
      create: jest.fn()         
    },
    .
    .
    .
  }
});

const createTestProps = (props: Object) => ({
    .
    .
    ...props
  });
  let props = createTestProps({});
it('renders correctly', () => {
    const tree = renderer.create(<LoginScreen {...props}/>).toJSON();
    expect(tree).toMatchSnapshot();
});

As you can see the problem is here:

style={styles.container} 

the method create from the StyleSheet mock returns undefined so when container is called the error happens. How can I fix this?


Viewing all articles
Browse latest Browse all 6208

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>