【发布时间】:2021-06-07 11:52:49
【问题描述】:
我刚刚上过关于 Javascript 和 Jest 的速成课程,所以我对它很陌生。我以为我在使用 jest 的测试文件格式上遇到了一些问题。
这是 fizzbuzz 问题,我知道这很容易,但我的问题是关于开玩笑测试。它显示:
Jest encountered an unexpected token. This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
我认为导入和导出的使用是正确的,对吧?
[fizzbuzz.test.js]
import { fizzbuzz } from "./fizzbuzz";
describe("fizzbuzz", () => {
it("should return the numbers passed in that are not divisible by 3 or 5", () => {
expect(fizzbuzz(1)).toBe(1);
expect(fizzbuzz(2)).toBe(2);
expect(fizzbuzz(4)).toBe(4);
});
it("should return 'fizz' if the number passed in is divisible by 3", () => {
expect(fizzbuzz(3)).toBe("fizz");
expect(fizzbuzz(6)).toBe("fizz");
});
it("should return 'buzz' if the number passed in is divisible by 5", () => {
expect(fizzbuzz(5)).toBe("buzz");
expect(fizzbuzz(10)).toBe("buzz");
});
it("should return 'fizzbuzz' if the number passed in is divisible by 3 and 5", () => {
expect(fizzbuzz(15)).toBe("fizzbuzz");
});
});
作为参考,这是我的 [fizzbuzz.js]。
export function fizzbuzz() {
for (let i = 1; i <= 100; i++){
if(i%3 === 0 && i % 5 === 0){
console.log("Fizzbuzz");
} else if (i % 3 === 0){
console.log("Fizz");
} else if (i % 5 === 0){
console.log("Buzz");
} else {
console.log(i);
}
}
}
我是在开源网站上解决的,所以有一些配置。 [.eslintrc.json]
{
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module"
},
"rules": {
"semi": "error"
}
}
[cyber-dojo.sh]
ln -s /etc/jest/node_modules ${CYBER_DOJO_SANDBOX}/node_modules
npm run lint
npm run test
[package.json]
{
"scripts": {
"lint": "eslint --config ${CYBER_DOJO_SANDBOX}/.eslintrc.json /**/*.js",
"test": "jest --coverage"
},
"jest": {
"coverageReporters": [ "text" ]
}
}
【问题讨论】:
-
您似乎有一个错字。
i = 1, i <改用i = 1; i <? -
错误是否说明了意外的令牌是什么?
-
语法错误:不能在模块外使用 import 语句。所以我觉得不能用import,应该怎么修改
-
这意味着您需要编译javascript。你在用
babel-jest吗? github.com/vuejs/vue-cli/issues/1584 -
@evolutionxbox 不。我想我需要在那个开源网站上使用这些配置。我正在尝试使用模块导出。
标签: javascript unit-testing testing jestjs