Jest测试文件未获取正确返回值问题求助
问题:Jest测试中模块导出导致的变量混淆问题
我确信这是个容易修复的问题,但卡了好一阵。我用Jest编写后端测试文件,以下是我的代码:
测试文件 background.test.js
const fileConnection = require('../background'); const firebaseConnection = require('../background'); const stripeConnection = require('../background'); test('File Test', () => { expect(fileConnection).toBe(true); }); describe('Background Test', () => { test('Firebase connection', async () => { expect(firebaseConnection).not.toBe(null); }); test('Stripe and Back-End connection', async () => { expect(stripeConnection).not.toBe(null); }); });
模块文件 background.js
import { db } from 'firebase/firestore'; let test = false; function fileConnection() { test = true; return test; } function firebaseConnection() { try { return db; } catch (error) { return null; } } function stripeConnection() { // 后端Stripe连接地址已隐藏 // 需要检查连接是否正常 try { fetch('CENSORED'); return 'Stripe connection is working'; } catch (error) { return null; } } module.exports = (fileConnection, firebaseConnection, stripeConnection);
遇到的错误
✕ File Test (4 ms) Background Test ✓ Firebase connection (1 ms) ✓ Stripe and Back-End connection (1 ms) ● File Test expect(received).toBe(expected) // Object.is equality Expected: true Received: [Function stripeConnection] 7 | 8 | test('File Test', () => { > 9 | expect(fileConnection).toBe(true); | ^ 10 | }); 11 | 12 | describe('Background Test', () => { at Object.toBe (src/test/background.test.js:9:26)
可以看到File Test拿到的是stripe connection的结果,我觉得是导出方式的问题。试过修改导出方式,但搞不懂为什么Firebase连接没报错,只有Stripe的有问题,复制代码风格也没用,求帮忙。
问题分析与修复
1. 导出方式错误是核心问题
你在background.js里的导出写法错误:
module.exports = (fileConnection, firebaseConnection, stripeConnection);
这是逗号表达式,逗号表达式会返回最后一个操作数的值,也就是stripeConnection函数。所以你三次require拿到的都是同一个函数,这就是为什么File Test里的fileConnection实际是stripeConnection函数,导致断言失败。
另外,测试里直接断言导出的变量是true,但fileConnection是个函数,你根本没调用它,就算导出正确,断言也会失败。
2. 修复导出方式
把background.js的导出改成对象形式,确保每个函数都能被正确引用:
module.exports = { fileConnection, firebaseConnection, stripeConnection };
3. 修正测试文件的引用与断言
测试里需要从导出对象中解构出对应函数,并且调用函数后再断言结果:
const { fileConnection, firebaseConnection, stripeConnection } = require('../background'); test('File Test', () => { // 调用函数获取返回值后再断言 expect(fileConnection()).toBe(true); }); describe('Background Test', () => { test('Firebase connection', () => { expect(firebaseConnection()).not.toBe(null); }); test('Stripe and Back-End connection', async () => { // Stripe连接是异步操作,需要等待结果 const result = await stripeConnection(); expect(result).not.toBe(null); }); });
4. 修复Stripe连接的异步问题
原来的stripeConnection使用fetch但未等待异步操作完成,会直接返回字符串,需要改成异步函数:
async function stripeConnection() { try { const response = await fetch('CENSORED'); // 检查请求是否成功 if (!response.ok) throw new Error('Stripe连接请求失败'); return 'Stripe connection is working'; } catch (error) { return null; } }
内容的提问来源于stack exchange,提问作者ElGonan
相关产品推荐
相关产品推荐

