【问题标题】:How to force Jest to see nested javascript function?如何强制 Jest 查看嵌套的 javascript 函数?
【发布时间】:2020-03-09 17:32:28
【问题描述】:

我的项目中有这样的结构

|...
|Utils
    | Utils.js
    | Utils.test.js
|...

Utils.js我有func,我要测试:

export const getSurroundingCells = (numRows, numCols, shipPositions) => {
    ...
    // some logic that calls cellIsSuitable()
    ...
    const cellIsSuitable = (position, shipPositions) => {
        ...
        // some logic that uses numRows, numCols
        ...
    }
}

当我想通过JestUtils.test.js 测试它时:

import {getSurroundingCells} from "./Utils";

const shipPositions = [[1, 1], [1, 2], [1, 3]];
const expectedSurroundingCells = [[2, 1], [2, 0], [1, 0], [0,0], [0,1], [0,2], [2,2]];

test('takes positions and returns surrounding cells', () => {
    expect(getSurroundingCells(10, 10, shipPositions)).toBe(expectedSurroundingCells);
});

我明白了:

ReferenceError: cellIsSuitable 未定义

如何强制Jest 看到我的嵌套函数cellIsSuitable

附:我的项目自举with create-react-app

【问题讨论】:

    标签: javascript jestjs create-react-app


    【解决方案1】:

    将其移至顶部或使其成为常规的function,以便将其吊起。函数在你使用后被赋值,但变量被声明。

    export const getSurroundingCells = (numRows, numCols, shipPositions) => {
    
        const cellIsSuitable = (position, shipPositions) => {
            ...
            // some logic that uses numRows, numCols
            ...
        }
    
        ...
        // some logic that calls cellIsSuitable()
        ...
    }
    

    【讨论】:

    • 非常感谢!它有帮助!
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2020-10-19
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2022-10-21
    相关资源
    最近更新 更多