如何测试节点的fs.watch()?

问题描述 投票:0回答:1

我有一个使用fs.watch的功能。下面的示例。

function listenToFileChange() {
  fs.watch(fileLocation, "utf-8", async function(event, fileName) {
    if (event === "change") {
      dbUp.push(fileName, function() {});
    }
  });
}

我正在尝试使用玩笑来测试;但我不清楚如何正确执行。存在可能的循环。

jest.mock("loadBaselineFile", () => jest.fn());

describe("Tests listenToFileChange", () => {
  test(`GIVEN endpoint /info
        WHEN make a request and database and data loader are healthy 
        THEN return an answer with status: pass, statusCode: 200, type:application/health+json`, async () => {
    listenToFileChange();
    fs.writeFileSync(
      `dataLoader/1.json`,
      "{id: '1', amount: '12'}",
      "utf8"
    );
    expect(loadBaselineFile.mock.calls.length).toBeCalledWith(1);
  });

}); 

有人可以帮助我了解如何正确测试此方法并确保我的测试性能良好。

javascript node.js jestjs
1个回答
0
投票
您需要回调:

function listenToFileChange(cb) { fs.watch(fileLocation, "utf-8", async function(event, fileName) { if (event === "change") { dbUp.push(fileName, cb); } }); }

因此,更改文件后,您可以在测试中注意到它:

listenToFileChange(()=>{ changed = true; // done(); });

由于这是测试异步功能,因此您需要调用类似“ done();”的名称活动启动时。如果未调用“ done()”,则测试超时将使其失败。
© www.soinside.com 2019 - 2024. All rights reserved.