首页 > 解决方案 > 我正在尝试将函数从上下文导出到另一个文件以与 jest 一起使用

问题描述

我想用 jest 在我的测试文件中运行一些函数。我是新手,所以请善待。我正在从我的应用程序的上下文文件中导入此函数。

let isProduction2 = () => {
    if (production) {
        return true
    } else {
        return false
    }
}

export {
    ProductProvider,
    ProductConsumer,
    ProductContext,
    isProduction2
};

import {
    isProduction2
} from './context'

test('Fake Test', () => {
    expect(isProduction2).toBeTruthy();
});
//Error   Jest encountered an unexpected token

这通常意味着您正在尝试导入 Jest 无法解析的文件,例如它不是纯 JavaScript。

默认情况下,如果 Jest 看到 Babel 配置,它将使用它来转换您的文件,而忽略“node_modules”。

标签: reactjsunit-testingjestjs

解决方案


问题是你没有isProduction2在你的期望语句中执行你的函数(即)。您目前只是传递一个参考。

代替

test('Fake Test', () => {
    expect(isProduction2).toBeTruthy();
});

它应该是

test('Fake Test', () => {
    expect(isProduction2()).toBeTruthy();
    //note the `()` after function name. This executes it and returns the result.
});

推荐阅读