【问题标题】:Jest test case error in react-native using external plugin使用外部插件在 react-native 中开玩笑测试用例错误
【发布时间】:2017-07-25 06:53:33
【问题描述】:

我正在使用 react-native init 创建一个 react-native 项目。我正在使用https://github.com/andpor/react-native-sqlite-storage 库进行 SQLite 绑定。

我有一个 DbConnector.jest-test.js 单元测试文件。内容是

import DbConnector from '../app/components/DbConnector.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () => {
const tree = renderer.create(
<DbConnector />
);
});

当我运行 jest 时,即使默认 node_modules 被忽略,我也会收到以下错误。我在 package.json 中使用 react-native 预设

Test suite failed to run

ReferenceError: window is not defined

  at Object.<anonymous> (node_modules/react-native-sqlite-storage/lib/sqlite.core.js:53:10)
  at Object.<anonymous> (node_modules/react-native-sqlite-storage/sqlite.js:10:12)
  at Object.<anonymous> (app/components/DbConnector.js:3:31)

Test Suites: 1 failed, 1 total

DbConnector.js 中的导入如下:

import React, { Component } from 'react'
import { AppRegistry, StyleSheet, Text, View, TextInput, Button, Alert, 
AsyncStorage } from 'react-native'
import SQLite from 'react-native-sqlite-storage'

【问题讨论】:

    标签: javascript android sqlite react-native jestjs


    【解决方案1】:

    您应该在测试之前尝试模拟 react-native-sqlite-storage。

    jest.mock('react-native-sqlite-storage');
    

    【讨论】:

      【解决方案2】:

      您的问题 window is not defined 似乎来自此行:https://github.com/andpor/react-native-sqlite-storage/blob/master/lib/sqlite.core.js#L53

      您的测试似乎缺少 react-native 的导入,应该如下所示:

      import 'react-native';
      import renderer from 'react-test-renderer';
      

      如果这不起作用,您可以按照以下步骤使用 JSDOM from this guide(来自 Enzyme,但可能仍然有帮助!)

      【讨论】:

        猜你喜欢
        • 2020-04-20
        • 2017-08-25
        • 1970-01-01
        • 2018-02-09
        • 2017-07-13
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多