玩笑测试中的错误:TypeError:无法读取未定义的属性“容器”

时间:2019-11-26 04:54:36

标签: typescript react-native jestjs

我正在尝试使用玩笑来测试一个打字稿react-native类,但是测试没有通过。

这是课程:

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

但是我遇到了错误:

TypeError: Cannot read property 'container' of undefined

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

测试就是这个:

/**
 * @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();
});

如您所见,问题出在这里:

style={styles.container} 

从StyleSheet模拟创建的方法返回未定义,因此在调用容器时会发生错误。我该如何解决?

1 个答案:

答案 0 :(得分:0)

尝试

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