简体   繁体   English

Mocha测试API没有响应

[英]Mocha testing API gives no response

I'm trying to test a node API in mocha, but I get no response from the API request that works fine in browser. 我正在尝试在Mocha中测试节点API,但是没有收到在浏览器中正常运行的API请求的响应。

Here is the response in browser: 这是浏览器中的响应:

Response in browser: {"succes":true} 浏览器中的响应: {“ succes”:true}

And this is the API test that is not working: 这是不起作用的API测试:

var request = require("request");
var expect = require("chai").expect;

describe("API TEST", function(){
    it("Should return true", function(done){

        request.get({ url: "https://skilltree.benis.hu/apitest" },
            function(error, response, body) {
                    console.log(response);
                done();
            });
    });
});

Result: 结果:

API TEST -> undefined (response=undefined) API测试->未定义(响应=未定义)

But the testing syntax seems fine, since it works with a public API: 但是测试语法看起来不错,因为它可以与公共API一起使用:

describe("API TEST", function(){
        it("Should return true", function(done){

        request.get({ url: "https://anapioficeandfire.com/api/characters/583" },
            function(error, response, body) {

                    console.log(response);
                done();
            });
    });
});

Result: Result was a bunch of response data. 结果:结果是一堆响应数据。

Tried to test it in POSTMAN, MIGHT have found the issue, not sure: Couldn't get response. 试图在POSTMAN中进行测试,MIGHT已找到问题,不确定:无法获得响应。

Possible solutions: 可能的解决方案:

Turn off ssl certificate verification <- did this one Turned off SSL Certificate verification in postman, and it worked: 关闭ssl证书验证<-这样做是在邮递员中关闭了SSL证书验证,它的工作原理是:

Response was the same as in browser: {"succes":true} 响应与浏览器中的响应相同: {“ succes”:true}

I tried to find a way to disable it in code too for testing, but I had no luck finding one. 我试图找到一种在测试中也将其禁用的方法,但是我没有运气。 This is pretty much the first time I am testing anything. 这几乎是我第一次测试任何东西。

Your assumption is correct in that it is a certificate verification related issue. 您的假设是正确的,因为它是与证书验证有关的问题。 I believe this should work: 我相信这应该有效:

 it.only("Should return true", function(done){
     process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
     request.get({ url: "https://skilltree.benis.hu/apitest" },
     function(error, response) {
       console.log(response.body);
       done();
     });
 });

When I run it, I get {"succes":true} . 运行它时,我得到{"succes":true}

Note, this is for demo purposes only, the process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; 注意,这仅用于演示目的, process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; shouldn't be part of every test, but rather defined at a higher level, so that it only runs once. 不应作为每个测试的一部分,而应在更高的级别进行定义,以便它只能运行一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM