带有Jest ES6模块的Javascript测试单元

时间:2019-01-01 17:58:26

标签: javascript ecmascript-6 jestjs babel testunit

在Google上进行搜索后,太多不同的帖子无法选择清晰,最新的解决方案...

我编写了3个测试来检查不同的可能性

============。测试1 OK ================

// helloJest.js

function sayHello() {
  return "hello there jest"
}
module.exports = sayHello;

// helloJestTest

const sayHello = require('../../src/client/js/helloJest');
test('string returning hello there jest', () => {// 
  expect(sayHello()).toEqual('hello there jest');
});

============。测试2失败================

// helloJest.js

function sayHello() {
  return "hello there jest"
}
export default { sayHello }; // <= changed

// helloJestTest

const sayHello = require('../../src/client/js/helloJest');
test('string returning hello there jest', () => {// 
  expect(sayHello()).toEqual('hello there jest');
});

TypeError: sayHello is not a function

      3 |
      4 | test('string returning hello there jest', () => {//
    > 5 |   expect(sayHello()).toEqual('hello there jest');
        |          ^
      6 | });
      7 |

============。测试3失败================

// helloJest.js

function sayHello() {
  return "hello there jest"
}
export default { sayHello }; //  <= changed

// helloJestTest

import { sayHello } from '../../src/client/js/helloJest'; // <= changed
test('string returning hello there jest', () => {// 
  expect(sayHello()).toEqual('hello there jest');
});

    TypeError: (0 , _helloJest.sayHello) is not a function

      3 |
      4 | test('string returning hello there jest', () => {//
    > 5 |   expect(sayHello()).toEqual('hello there jest');
        |          ^
      6 | });

如何正确通过测试3 ???

我正在使用以下软件包

package.json

"babel-core": "^6.26.3",
"babel-jest": "^23.6.0",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
...
"jest": {
    "moduleFileExtensions": ["js"],
    "transform": { "^.+\\.js?$": "babel-jest" },
    "testRegex": "/tests/.*\\.(js)$"
  }

我有

.babelrc

{
  "presets": ["env"]
}

2 个答案:

答案 0 :(得分:5)

您正在那里的几个地方绊倒。主要是:请勿将{}与默认的导入/导出一起使用。

此:

export default { sayHello };

导出对象作为模块的默认导出。该对象具有引用该函数的单个属性sayHello。要将 function 设置为默认导出,请不要使用{}

export default sayHello;

然后,在导入时,如果要使用默认导入,请不要使用{}

import sayHello from '../../src/client/js/helloJest';

如果要导出以命名的导出,请使用{}

export { sayHello };

import { sayHello } from '../../src/client/js/helloJest';

插拔器上的两个示例:https://embed.plnkr.co/f8PhOhULphQUrVXwdXF3/

答案 1 :(得分:1)

测试2

默认情况下,您确实导出具有单个属性(即sayHello函数)的对象,因此应通过以下方式来引入该对象:

const { sayHello } = require('../../src/client/js/helloJest');

测试3

再次按照上述步骤导出。 在这种情况下,您可以按以下方式导入它:

import Hello from '../../src/client/js/helloJest';

然后您应该可以将func用作:

Hello.sayHello