首页 > 解决方案 > 测试文件时遇到错误

问题描述

我刚刚上过关于 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"
    }
}

[网络道场.sh]

ln -s /etc/jest/node_modules ${CYBER_DOJO_SANDBOX}/node_modules
 
npm run lint
npm run test

[包.json]

{
  "scripts": {
    "lint": "eslint --config ${CYBER_DOJO_SANDBOX}/.eslintrc.json /**/*.js",
    "test": "jest --coverage"
  },
  "jest": {
    "coverageReporters": [ "text" ]
  }
}

标签: javascriptunit-testingtestingjestjs

解决方案


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

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

应该

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

注意从,到的变化;


推荐阅读