node.js - 使用 Mocha 运行类似的测试

标签 node.js testing mocha.js

背景

我正在从一个维基百科中获取信息,在我真正这样做之前,我想确保我可以连接到维基百科服务器。

最好的方法是什么?使用 mocha使用我的 nodejs 应用程序进行测试!

目标

我有一个配置文件,其中有一个包含我想要的所有链接的对象。我有一个名为“连接”的电池组,我希望每次测试都尝试连接到 Wikia。

{
    "sources": {
        "wikia": {
            "link": "http://warframe.wikia.com/wiki",
            "pages": {
                "mods_2.0": "/Mods_2.0",
                "warframe_mods": "/Category:Warframe_Mods",
                //more links follow
            }
        }
    }
}

问题

这里的问题是我不想为十几个 wikia 页面编写和复制相同的测试。我想避免重复。

我的解决方案是将每个 it 放在一个循环中,但是,代码会中断,因为我的 wikiaPages 数组始终未定义,即使我使用 before() 函数。

代码

let assert = require("assert");
let superagent = require("superagent");
let jsonfile = require("jsonfile");

const SCRAPER_CONFIG_FILE = "./scraperConfig.json";

describe("connection", () => {

    let wikiaUri;
    let wikiaPages;
    let completeUri;

    before(() => {
        let config = jsonfile.readFileSync(SCRAPER_CONFIG_FILE);
        wikiaUri = config.sources.wikia.link;
        wikiaPages = Object.values(config.sources.wikia.pages);
    });

    for(let pageUri of wikiaPages) {

        completeUri = wikiaUri + pageUri;

        it("connects to " + completeUri, done => {
            superagent.get(completeUri, (error, res) => {
                assert.ifError(error);
                assert.equal(res.status, 200);
                done();
            });
        });
    }
});

问题

  • 如何修复此代码,使其正常工作?

最佳答案

将它移出你的 before block :

describe("connection", () => {
    const config = jsonfile.readFileSync(SCRAPER_CONFIG_FILE);
    const wikiaUri = config.sources.wikia.link;
    const wikiaPages = Object.values(config.sources.wikia.pages);

    before(() => {
    });

    for(let pageUri of wikiaPages) {

        completeUri = wikiaUri + pageUri;

        it("connects to " + completeUri, done => {
            superagent.get(completeUri, (error, res) => {
                assert.ifError(error);
                assert.equal(res.status, 200);
                done();
            });
        });
    }
});

关于node.js - 使用 Mocha 运行类似的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41940096/

相关文章:

node.js - 在 Node.js 中使用 sqlite 模块时出现问题

javascript - 在 NodeJS 中使用文本文件时如何有效地锁定它?

iphone - 从 iTunes 上传测试 iPhone/iPod 应用程序?

.net - 针对锁定的文件测试您的代码?

c# - 使用 Asp.Net 核心和 Nunit 的测试未在 TestExplorer 中显示

asynchronous - 开 Jest 或 Mocha : Dynamically create tests based on async initialization

mysql - 无法以同步模式运行 Mocha.js

node.js - 强制 http.globalAgent.keepAlive = true

node.js - 如何允许客户在服务网站上为自己的页面设置自定义域?

node.js - 使用虚拟数据库在自己的环境中测试express.js应用程序