我正在尝试使用TypeScript编写利用sqlite3的类的单元测试。
该类本身可以正确利用sqlite3,但是当我尝试测试使用sqlite3的函数时,出现以下错误消息:
Test suite failed to run
package.json does not exist at C:\...\node_modules\sqlite3\package.json
但是,当我单击该链接时,它将打开package.json文件。实际上确实如此。
正在测试的类的简化版本如下:
import sqlite3 from "sqlite3";
import path from "path";
import fs from "fs";
export class DataManager {
database_path: string;
gamertags: { [key: string]: any };
api: object;
constructor() {
//Prepare database
this.database_path = path.join(__dirname, "..", "data", "DBName.db");
}
public mainloop = async () => {
//Setup database
this.setup_db(this.database_path);
};
setup_db = async (db_path: string) => {
//Create data directory if it doesn't exist
if (!fs.existsSync(path.join(__dirname, "..", "data"))) {
fs.mkdirSync(path.join(__dirname, "..", "data"));
}
//Get read/write connection to database
const db = new sqlite3.Database(db_path);
//Serialize context to make sure tables are created in order
db.serialize(() => {
//Create table_1
db.run(`sql_query...`);
//Create table_2
db.run(`sql_query...`);
});
};
}
我的单元测试:
import { DataManager } from "../../core/dataManager";
import { mocked } from "ts-jest/utils";
import fs from "fs";
import sqlite3 from "sqlite3";
jest.mock("fs");
jest.mock("sqlite3");
let manager: DataManager;
const fake_database_path: string = "fake/database/path";
describe("datamanager.setup_db", () => {
beforeEach(() => {
jest.resetAllMocks();
manager = new DataManager();
manager.database_path = fake_database_path;
});
it("should create a new database file if one does not exist", async () => {
//Arrange
mocked(fs).existsSync = jest.fn().mockReturnValue = false as any;
mocked(sqlite3).Database = jest.fn() as any;
//Act
await manager.setup_db(fake_database_path);
});
});
我只是不确定到底是什么因素导致sqlite3无法找到自己的package.json
。我的其他依赖项似乎都没有引起大惊小怪,而sqlite3却引起了大惊小怪。