【问题标题】:Error in jest test: TypeError: Cannot read property 'container' of undefined开玩笑测试中的错误:TypeError:无法读取未定义的属性“容器”
【发布时间】:2020-03-21 11:05:01
【问题描述】:

我正在尝试使用 jest 测试 typescript 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 模拟创建的方法返回未定义,因此当调用容器时会发生错误。我该如何解决这个问题?

【问题讨论】:

  • 反应版本是“react”:“16.9.0”,导航抽屉版本是“react-navigation-drawer”:“^2.3.3”,我用的是“jest” :“^24.1.0”,有人吗?

标签: typescript react-native jestjs


【解决方案1】:

试试

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

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 2019-02-16
    • 2020-11-19
    • 2018-06-17
    • 1970-01-01
    • 2019-08-08
    • 2020-07-10
    • 2017-12-15
    • 2017-09-19
    相关资源
    最近更新 更多