You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

yarn hardhat test报Unexpected end of JSON input错误如何解决

问题背景

从npm切换到Yarn进行Solidity开发,使用全新初始化的Hardhat官方示例项目时,执行yarn hardhat test触发如下报错:

An unexpected error occurred:

SyntaxError: Error parsing /Users/xy/Desktop/program/test_test/node_modules/loupe/package.json: Unexpected end of JSON input
    at parse (<anonymous>)
    at readPackage (node:internal/modules/cjs/loader:304:20)
    at resolveExports (node:internal/modules/cjs/loader:479:15)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/xy/Desktop/program/test_test/node_modules/chai/lib/chai/utils/inspect.js:5:13)
    at Module._compile (node:internal/modules/cjs/loader:1103:14) {
  path: '/Users/xy/Desktop/program/test_test/node_modules/loupe/package.json'
}
error Command failed with exit code 1.
已完成的前置验证
  • 同项目下执行yarn hardhat compile可正常运行,无报错
  • 切换为npm执行测试相关命令无任何异常
  • 测试脚本为Hardhat官方默认提供的Greeter合约测试样例,代码如下:
import { expect } from "chai";
import { ethers } from "hardhat";

describe("Greeter", function () {
  it("Should return the new greeting once it's changed", async function () {
    const Greeter = await ethers.getContractFactory("Greeter");
    const greeter = await Greeter.deploy("Hello, world!");
    await greeter.deployed();

    expect(await greeter.greet()).to.equal("Hello, world!");

    const setGreetingTx = await greeter.setGreeting("Hola, mundo!");

    // wait until the transaction is mined
    await setGreetingTx.wait();

    expect(await greeter.greet()).to.equal("Hola, mundo!");
  });
});
  • 移除测试脚本中chai相关的expect断言代码后,报错不再出现,初步定位问题与chai依赖有关
问题根因

报错指向chai的间接依赖loupe包的package.json文件内容截断、解析失败,属于Yarn安装依赖时偶发的单包拉取不完整问题:

  • hardhat compile流程不会加载chai及相关依赖,因此不会触发报错
  • npm安装时拉取的依赖包完整,因此切换npm执行测试无异常
  • 移除chai相关代码后不会加载loupe包,因此报错消失
解决步骤

按顺序执行以下操作即可修复:

  • 清理项目本地已安装依赖和Yarn锁文件,在项目根目录执行命令:
    rm -rf node_modules yarn.lock
    
  • 清理Yarn本地全局缓存,避免复用损坏的缓存包:
    yarn cache clean
    
  • 重新安装全量项目依赖:
    yarn install
    
  • 安装完成后重新执行测试命令yarn hardhat test即可正常运行。

如果执行完以上步骤仍偶发报错,可以手动强制安装完整版本的loupe包作为开发依赖,执行命令yarn add -D loupe@latest后再重试测试即可。


内容的提问来源于stack exchange,提问作者Xinyang12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 20:48:21