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

jtw3ybtb  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(82)

我不能在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.jsbabel.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上工作。我的配置文件中缺少了什么?

y0u0uwnf

y0u0uwnf1#

应该去ChatGPT这里是答案,以防有人想要它。
要将Jest配置为与ES6(ECMAScript 2015及更高版本)一起使用,您需要确保Jest可以在测试期间理解并转译您的ES6代码。以下是为ES6配置Jest的步骤:
1.安装所需的软件包:
确保安装了必要的包。您需要babel-jest来启用Jest以使用Babel进行转译。

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

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

{
  "presets": ["@babel/preset-env"]
}


此配置告诉Babel使用@babel/preset-env预设,它会根据您的目标环境自动确定所需的Babel插件。
1.更新Jest配置:
package.json中更新Jest配置或创建单独的jest.config.js文件。确保transform选项包括babel-jest Transformer。
如果使用package.json

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    }
  }
}


如果使用jest.config.js

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


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

module.exports = {
  presets: ['@babel/preset-env']
};


如果您使用.babelrc而不是babel.config.js,请确保babel-jest Transformer配置为使用它。
1.运行Jest测试:
有了这些配置,您应该能够使用以下命令运行Jest测试:

npm test


Jest现在应该在测试过程中使用Babel转译你的ES6代码。根据你的项目结构和需求调整配置。
所有测试结果现在都可以在ES6上运行:

> jest

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

相关问题