【问题标题】:jasmine spy not finding property茉莉花间谍没有找到财产
【发布时间】:2020-01-28 13:33:22
【问题描述】:

我有一个基本上看起来像这样的文件(缩短)

const octokit = new (require("@octokit/rest"))();
function buildRepo(name) {
  fs.promises
    .readFile("data/settings.json")
    .then(data => JSON.parse(data))
    .then(settings => settings.repositories.find(repo => repo.name === name))
    .then(repo => {
      let repoName = repo.url
        .substring(repo.url.lastIndexOf("/") + 1)
        .slice(0, -4);
      let jobName = repo.name;
      return octokit.repos
        .get({
          owner: "munhunger",
          repo: repoName
        })
        .then(({ data }) => {
          ...
        });
    });
}

module.exports = { buildRepo };

所以我想写一个测试,看看它如何处理从octokit.repos.get 函数获得的数据。但由于该函数将发布到 Internet 并查看 GitHub 存储库,因此我想模拟它。

我用 jasmine 运行了一些测试,我稍微阅读了一下,似乎 jasmine 应该能够为我模拟这个。

但是,我编写的测试似乎失败了。

const builder = require("./index");

describe("spyOn", () => {
  it("spies", () => {
    spyOnProperty(builder, "octokit");
    builder.buildRepo("blitzbauen");
  });
});

出现错误octokit property does not exist。我在这里做错了什么?我需要将octokit 添加到module.exports 吗?(这似乎很疯狂)

【问题讨论】:

    标签: javascript node.js unit-testing testing jasmine


    【解决方案1】:

    是的,您需要将 Octokit 添加到 module.exports,因为您现在只导出 buildRepo。 模块中未导出的任何内容都不能被其他模块直接访问,因此如果应该可以访问,则应该将其导出。

    或者,您可以使用 Jasmine 模拟整个 Octokit 模块,因此任何脚本的任何调用都会对模拟版本进行,但我不确定您将如何去做,因为我对 Jasmine 的经验是有限

    【讨论】:

    • 嗯,好吧。这让我对这个问题有了更多的理解:) 但似乎我真的需要模拟整个模块
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2012-08-15
    • 2018-03-02
    • 2014-03-18
    相关资源
    最近更新 更多