mocha-webpack单元测试与superagent

时间:2017-02-16 13:26:49

标签: javascript webpack mocha superagent mocha-webpack

我使用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和显示数据进行通信,但不能与测试进行通信。

我的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' }

每个人都有同样的问题?

0 个答案:

没有答案