1 javascript testunit babel ecmascript-6 jestjs
谷歌搜索选择一个清晰和最新的解决方案时,有太多不同的帖子......
我写了3个测试来检查不同的可能性
===========.测试1确定================
// helloJest.js
function sayHello() {
return "hello there jest"
}
module.exports = sayHello;
Run Code Online (Sandbox Code Playgroud)
// helloJestTest
const sayHello = require('../../src/client/js/helloJest');
test('string returning hello there jest', () => {//
expect(sayHello()).toEqual('hello there jest');
});
Run Code Online (Sandbox Code Playgroud)
===========.TEST 2 FAILING ================
// helloJest.js
function sayHello() {
return "hello there jest"
}
export default { sayHello }; // <= changed
Run Code Online (Sandbox Code Playgroud)
// 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 |
Run Code Online (Sandbox Code Playgroud)
===========.TEST 3 FAILING ================
// helloJest.js
function sayHello() {
return "hello there jest"
}
export default { sayHello }; // <= changed
Run Code Online (Sandbox Code Playgroud)
// 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 | });
Run Code Online (Sandbox Code Playgroud)
如何正确通过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)$"
}
Run Code Online (Sandbox Code Playgroud)
我有
.babelrc
{
"presets": ["env"]
}
Run Code Online (Sandbox Code Playgroud)
你在那里的几个地方绊倒了.主要:您不使用{}默认导入/导出.
这个:
export default { sayHello };
Run Code Online (Sandbox Code Playgroud)
将对象导出为模块的默认导出.该对象具有单个属性sayHello,指的是该函数.要使该函数成为默认导出,请不要使用{}:
export default sayHello;
Run Code Online (Sandbox Code Playgroud)
然后,在导入时,如果您想要默认导入,请不要使用{}:
import sayHello from '../../src/client/js/helloJest';
Run Code Online (Sandbox Code Playgroud)
如果要导出命名导出,请使用{}:
export { sayHello };
Run Code Online (Sandbox Code Playgroud)
和
import { sayHello } from '../../src/client/js/helloJest';
Run Code Online (Sandbox Code Playgroud)
关于plunker的例子:https://embed.plnkr.co/f8PhOhULphQUrVXwdXF3/
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |