【问题标题】:Encounter errors in jest for testing files测试文件时遇到错误
【发布时间】: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 &lt; 改用i = 1; i &lt;
  • 错误是否说明了意外的令牌是什么?
  • 语法错误:不能在模块外使用 import 语句。所以我觉得不能用import,应该怎么修改
  • 这意味着您需要编译javascript。你在用babel-jest吗? github.com/vuejs/vue-cli/issues/1584
  • @evolutionxbox 不。我想我需要在那个开源网站上使用这些配置。我正在尝试使用模块导出。

标签: javascript unit-testing testing jestjs


【解决方案1】:

就像进化盒所说的那样;你在第 2 行有一个错字:

  for (let i = 1, i <= 100; i++){

应该是

  for (let i = 1; i <= 100; i++){

注意从 ,; 的变化

【讨论】:

  • 感谢您的指出。但同样的错误信息仍然存在。
  • 请标记错别字,而不是回答?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多