【问题标题】:Difference between import and require in jest开玩笑的 import 和 require 之间的区别
【发布时间】:2016-06-22 14:09:32
【问题描述】:

我正在使用 react-native-router-fluxreact-redux 为 react-native 项目编写我的第一个测试

我的代码类似于

jest.autoMockOff();
jest.setMock('react-native', {
    NativeModules: {}
});
jest.setMock('react-native-router-flux', {
    Actions: {}
});

const mockStore = require('../../mock/Store');
const actions = require('../myActions');
...
// Some tests that test if the right actions are dispatched.

上述方法有效,但是当我使用 ES6 import 而不是 require 时,我遇到了问题。

如果我替换

const actions = require('../myActions');

import * as actions from "../myActions"

我收到以下错误。

Runtime Error
  - Error: Cannot find module 'ReactNative' from 'react-native.js'
        at Resolver.resolveModule (node_modules/jest-cli/node_modules/jest-resolve/src/index.js:117:17)
        at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native.js:175:25)
        at Object.<anonymous> (node_modules/react-native-router-flux/src/Scene.js:10:18)

虽然我可以解决这个问题,但我很想了解失败的原因, 另请注意,我无法在.bablerc 文件中使用es2015 预设转译react-native-router-flux,我认为我将不得不忍受这个限制(无法转译react-native-router-flux)。

myActions.js 看起来像

import {Actions} from 'react-native-router-flux';
export function searchRequest() {
    return {
        type: "search_request"
    }
}

export function searchRequestFailure(error) {
    return {
        type: "search_request_failure",
        error: error.toString()
    }
}

export function searchRequestSuccess(payload) {
    return {
        type: "search_request_success",
        payload: payload
    }
}

export function search(nameOrAddress) {
    return dispatch => {
        dispatch(searchRequest())
        return fetch("http://localhost:8080/search", {
            method: "GET"
        }).then((response) => {
            return response.json()
        }).then((responseData) => {
            dispatch(searchRequestSuccess(responseData))
            Actions.list() //react-native-router-flux dependency
        }).catch(error =>  {
            dispatch(searchRequestFailure(error))
        })
    }
}

使用 react-native 0.26 和 jest 12.1.1

【问题讨论】:

    标签: react-native jestjs


    【解决方案1】:

    这不是正确的 ES6 转换。

    const actions = require('../myActions'); // requires the defaultMember of the exported module and
    
    //ES6 (ES2015) equivalent is 
    import actions from '../myActions';
    

    https://developer.mozilla.org/en/docs/web/javascript/reference/statements/import

    【讨论】:

    • 链接说import * as name from "module-name"是一个有效的语法;我在myActions 中没有默认导出,所以我需要通配符从中导入所有操作。
    • 我已经编辑了描述以包含 myActions.js
    • 该错误似乎与导入行无关。你如何使用你的行动?你也可以分享那个代码吗?
    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2019-03-03
    • 2021-11-14
    • 2021-05-07
    • 2011-10-31
    • 2016-10-05
    • 2018-03-22
    • 2015-11-19
    相关资源
    最近更新 更多