【发布时间】:2019-05-28 14:10:27
【问题描述】:
谷歌搜索时有太多不同的帖子,无法选择清晰且最新的解决方案...
我写了 3 个测试来检查不同的可能性
===========。测试 1 正常 =================
// 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 | });
如何正确通过TEST 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和3有什么区别?你似乎只做了一半的改变;在这两种情况下,默认导出都是 object,而不仅仅是函数。
-
你有没有尝试在你的 test2 中做
const { sayHello } = require('../../src/client/js/helloJest'); -
在 2. (export default ES6, require()) In 3. (export default ES6, import ES6)
标签: javascript ecmascript-6 jestjs babeljs testunit