1

我使用 mocha-webpack 对外部 api 进行单元测试,并使用 superAgent 进行我的 ajax 请求。我做了2个测试:

 const request = require("superagent");
var chai = require('chai')
    , expect = chai.expect
    , should = chai.should();
var chaiAsPromised = require("chai-as-promised");
var chaiThings = require("chai-things");

chai.use(chaiThings);
chai.use(chaiAsPromised);

describe("Service API getData url", function () {
var response;

before(function(done) {
    request
        .get('http://www.google.fr/')
        .withCredentials()
        .end(function(res){
            if ( err ) {
                console.log("err", err)
            } else {
                response = res;
                done();
            }
        });
});

it("response is 200", function() {
    expect(response.status).to.equal(200);
});

it("response type", function() {
    expect(response.type).to.equal("text/html");
});

但它不起作用。

 error : err { Error: Request has been terminated
    Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.

在前面,我没有问题,我可以与 superAgent et 显示数据通信,但不能与测试通信。

我的 webpack 配置,我有:

 headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true"
    },
    inline: false,
    noCredentials: true,

新测试:

var response;
    before(function(done) {  request.get('https://httpbin.org/get').end(function(err, res){
                if ( err ) {
                    console.log("err", err)
                } else {
                    response = res;
                    done();
                }
            });
    });  it("response is 200", function() {
        expect(response.status).to.equal(200);
    });

    it("response type", function() {
        expect(response.type).to.equal("application/json");
    });

测试成功

新测试:

var response;

    before(function(done) {

        request.get('http://api.football-data.org/v1/fixtures?timeFrame=n1').set('X-Auth-Token', 'myid')
            .end(function (err, res) {
                if ( err ) {
                    console.log("err", err)
                } else {
                    response = res;
                    done();
                }
            });

 it("response is 200", function() {
        expect(response.status).to.equal(200);
    });

测试错误:

{ Error: Request has been terminated
Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.
 crossDomain: true,
  status: undefined,
  method: 'GET',
  url: 'http://api.football-data.org/v1/fixtures?timeFrame=n1' }

每个人都有同样的问题吗?

4

0 回答 0