使用 ES6 导入时 Jest 手动模拟不起作用

问题描述 投票:0回答:1

我遇到了这个问题,无法在 ES6 中使用 Jest,但它在 CommonJS 中对我有用!

如果我使用标准 Common JS

require
我可以使用手动模拟和玩笑,这样这个目录就可以看到
__mocks__
但 ES6 不起作用

这是文件结构

-root
--src
---currency.js
---currency.test.js
---utils
----fetch-data.js
----__mocks__
-----fetch-data.js

所以外部 REST-API 位于

utils/fetch-data.js
所以我试图在我的
currency.test.js
中模拟这个文件,如果我使用 CommonJS 它可以工作,这里是它的代码集

/utils/fetch.data.js

const axios = require("./axios");
// import axios from "./axios"; // <-- when I try ES6 I flip this on and comment over the CommonJS


const fetchData = async () => {
    const rates = await axios.get('https://api.ratesapi.io/api/latest')
    return rates
}
 module.exports = fetchData;
//export default fetchData; // <-- when I try ES6 I flip this on and comment over the CommonJS

mocks中的模拟测试

utils/

mocks/fetch-data.js

const fetchData = jest.fn(() => { Promise.resolve({ status: "MOCK", data: {} }) }); module.exports = fetchData; // export default fetchData; // <-- when I try ES6 I flip this on and comment over the CommonJS
然后在货币文件里面
货币.js

// import fetchData from "./utils/fetch-data"; // <-- when I try ES6 I flip this on and comment over the CommonJS const fetchData = require("./utils/fetch-data"); module.exports = class CurrencyComparison { // export default class CurrencyComparison { // <- ES6 export when I want to try use ES6 I flip this on and comment the module.exports which is CommonJS constructor(salary) { this.salary = salary } fetchCurrentExchange = async () => { // <-- we are testing this as fetchData is from an API return await fetchData().then(res => { return [res.data.rates, res.status] }) } }
现在测试
货币.test.js

// import CurrencyComparison from "./currency_comparison"; // <-- when I try ES6 I flip this on and comment over the CommonJS const CurrencyComparison = require("./currency_comparison"); // Task 10: Import and mock fetchData const fetchData = require("./utils/fetch-data.js"); // import fetchData from "./utils/fetch-data.js"; // <-- when I try ES6 I flip this on and comment over the CommonJS jest.mock("./utils/fetch-data.js"); // not performing properly with ES6 const testSalary = new CurrencyComparison(50000); it("Receives current currency exchange data", async ()=>{ //arrange const mockResponse = { status : "Mock", data: { "base": "USD", "rates": { "CCD": 50, }, "date": "2021-05-17" } } const expectedValue = [{"CCD": 50}, "Mock"]; // Mock the resolved value of fetchData fetchData.mockResolvedValueOnce(mockResponse); // it fails here giving the clue that the __mocks__ folder is not used as the mocking with ES6. the test works with CommonJS //act const actualValue = await testSalary.fetchCurrentExchange() //assert expect(actualValue).toEqual(expectedValue); });
这是我如何设置 package.json 只查询最相关的代码!
包.json

"type": "module", "scripts": { "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" }, "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.23.7", "@babel/preset-env": "^7.23.7", "babel-jest": "^29.7.0", "jest": "^29.7.0" }, "jest": { "transform": {} }, "babel": { "presets": [ "es2015" ] }
我也有一个 .babelrc
.babelrc

{ "presets": ["@babel/preset-env"] }
我没有 jest.config.js 和 babel.config.js

ES6 的测试结果忽略其他测试 测试 ES6

FAIL src/currency.test.js the entire block of tests √ Gets conversion rate for currency (4 ms) √ Converts USD salary to hourly CAD pay (1 ms) √ Respond with different salaries based on currency (2 ms) × Receives current currency exchange data (1 ms) ● the entire block of tests › Receives current currency exchange data TypeError: fetchData.mockResolvedValueOnce is not a function 84 | 85 | // Mock the resolved value of fetchData > 86 | fetchData.mockResolvedValueOnce(mockResponse); | ^ 87 | 88 | 89 | //act at Object.<anonymous> (src/currency_comparison.test.js:86:15) Test Suites: 1 failed, 1 total Tests: 1 failed, 3 passed, 4 total Snapshots: 0 total Time: 0.563 s Ran all test suites.
这是相同代码但使用 CommonJS 的测试结果
测试通用

PASS src/currency.test.js the entire block of tests √ Gets conversion rate for currency (2 ms) √ Converts USD salary to hourly CAD pay √ Respond with different salaries based on currency (1 ms) √ Receives current currency exchange data (1 ms) Test Suites: 1 passed, 1 total Tests: 4 passed, 4 total Snapshots: 0 total Time: 0.596 s, estimated 1 s Ran all test suites.
我做错了什么

mocks手动模拟不能与ES6一起使用,但可以与标准CommonJS一起使用。我的配置文件等中缺少什么?

javascript unit-testing ecmascript-6 jestjs jest-fetch-mock
1个回答
0
投票
应该去chatGPT这里是答案,以防有人想要它。

要配置 Jest 以使用 ES6(ECMAScript 2015 及更高版本),您需要确保 Jest 在测试期间可以理解并转换您的 ES6 代码。以下是为 ES6 配置 Jest 的步骤:

    安装所需的软件包:
确保您已安装必要的软件包。您需要 babel-jest 才能使 Jest 使用 Babel 进行转译。

npm install --save-dev babel-jest @babel/core @babel/preset-env

    创建 Babel 配置文件:
在项目的根目录中创建一个 .babelrc 文件,其中包含以下内容:

{ "presets": ["@babel/preset-env"] }
此配置告诉 Babel 使用 @babel/preset-env 预设,它会根据您的目标环境自动确定所需的 Babel 插件。

    更新 Jest 配置:
更新 package.json 中的 Jest 配置或创建单独的 jest.config.js 文件。确保转换选项包含 babel-jest 变压器。

如果使用package.json:

{ "scripts": { "test": "jest" }, "jest": { "transform": { "^.+\\.jsx?$": "babel-jest" } } }
如果使用 jest.config.js:

module.exports = { transform: { '^.+\\.jsx?$': 'babel-jest' } };

    为 Jest 配置 Babel:
确保 Babel 配置为使用 babel.config.js 文件中的预设:

module.exports = { presets: ['@babel/preset-env'] };
如果您使用 .babelrc 而不是 babel.config.js,请确保 babel-jest 转换器配置为使用它。

    运行笑话测试:
完成这些配置后,您应该能够使用以下命令运行 Jest 测试:

npm test
Jest 现在应该在测试过程中使用 Babel 转译您的 ES6 代码。根据您的项目结构和要求调整配置。

chatGPT 的回答非常好

© www.soinside.com 2019 - 2024. All rights reserved.