我不能在ES6中使用Jest,但它在CommonJS中对我有效。
如果我使用标准CommonJS require
,我可以使用Jest手动模拟,所以这个目录是__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
中模拟此文件。
// /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
型
然后在货币文件中
// currency.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]
})
}
}
型
现在测试
// currency.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的,只输出最相关的代码!
// package.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(忽略其他测试)
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.
型
我做错了什么,Manual Mocking不能在ES6上工作,但可以在标准CommonJS上工作。我的配置文件中缺少了什么?
1条答案
按热度按时间y0u0uwnf1#
应该去ChatGPT这里是答案,以防有人想要它。
要将Jest配置为与ES6(ECMAScript 2015及更高版本)一起使用,您需要确保Jest可以在测试期间理解并转译您的ES6代码。以下是为ES6配置Jest的步骤:
1.安装所需的软件包:
确保安装了必要的包。您需要
babel-jest
来启用Jest以使用Babel进行转译。字符串
1.创建一个Babel配置文件:
在项目的根目录下创建一个
.babelrc
文件,包含以下内容:型
此配置告诉Babel使用
@babel/preset-env
预设,它会根据您的目标环境自动确定所需的Babel插件。1.更新Jest配置:
在
package.json
中更新Jest配置或创建单独的jest.config.js
文件。确保transform选项包括babel-jest
Transformer。如果使用
package.json
:型
如果使用
jest.config.js
:型
1.为Jest配置Babel:
确保Babel配置为使用
babel.config.js
文件中的预设:型
如果您使用
.babelrc
而不是babel.config.js
,请确保babel-jest
Transformer配置为使用它。1.运行Jest测试:
有了这些配置,您应该能够使用以下命令运行Jest测试:
型
Jest现在应该在测试过程中使用Babel转译你的ES6代码。根据你的项目结构和需求调整配置。
所有测试结果现在都可以在ES6上运行:
型