2017-01-17 30 views
0

我測試一個AJAX請求使用XMLHttpRequest言:諾克攔截了我的要求,但我的AJAX請求被示數出

export default function requestToTest() { 
    const xhr = new XMLHttpRequest(); 
    xhr.open('GET', 'https://example.com/service'); 

    xhr.onload =() => { 
    console.log('onload'); 
    // etc. 
    }; 

    xhr.onerror =() => { 
    console.log('onerror'); 
    // etc. 
    }; 

    xhr.send(); 
} 

所以我設置使用諾克(和摩卡)測試:

describe('requestToTest()',() => { 
    it('should handle a successful request',() => { 
    nock('https://example.com') 
     .log(console.log) 
     .get('/service') 
     .reply(200, { some: 'json' }); 

    requestToTest(); 

    expect(/* things I want to check */).to.be.true; 
    }); 
}); 

當我運行此測試時,xhr.onerror()發生火災,而不是xhr.onload()。但是,通過觀察Nock從log()調用的輸出,我確定地知道Nock攔截了我的AJAX請求,並且攔截的請求與Nock的預期URL匹配。

爲什麼xhr.onerror被調用而不是xhr.onload在我的測試中?

+0

我從來沒有完全弄清楚這一點,但我認爲這是因爲'XMLHttpRequest'只在瀏覽器環境中定義,而不是在Node.js.中定義。 – Kevin

回答

1

作爲解決方法,我使用了isomorphic-fetch庫。該庫是XMLHttpRequest用於製作AJAX請求的替代方法,專門用於在瀏覽器環境和Node.js /測試環境中以相同方式工作。

通常,使用旨在平滑瀏覽器中AJAX請求之間的差異並從測試環境發出請求的庫似乎是解決此問題的方案。