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
在我的測試中?
我從來沒有完全弄清楚這一點,但我認爲這是因爲'XMLHttpRequest'只在瀏覽器環境中定義,而不是在Node.js.中定義。 – Kevin