我是撰寫單元測驗的新手,我正在嘗試學習 Mocha 和 Chai。在我的 Node express 專案中,我創建了一個單元測驗,如下所示:
import { expect } from 'chai';
var EventSource = require('eventsource');
describe('Connection tests', () => { // the tests container
it('checks for connection', () => { // the single test
var source = new EventSource('http://localhost:3000/api/v1/prenotazione?subscribe=300');
source.onmessage = function(e: any) {
expect(false).to.equal(true);
};
});
});
http://localhost:3000/api/v1/prenotazione?subscribe=300測驗執行時 web 服務處于活動狀態,我可以看到 Mocha 確實呼叫了它,因為我的 web 服務記錄了傳入的請求。該網路服務使用SSE 協議,它從不關閉連接,但它會不時地通過同一連接發送資料。EventSource是實作 SSE 協議的客戶端類,當您在其中設定onmessage回呼時,它會連接到服務器。但是 Mocha 不會等待 web 服務回傳,并且測驗會通過我寫入expect函式呼叫的任何內容。例如,只是為了除錯測驗代碼本身,我什至寫了expect(false).to.equal(true);這顯然不可能是真的。但是,這是我在運行測驗時得到的:
$ npm run test
> crud@1.0.0 test
> mocha -r ts-node/register test/**/*.ts --exit
Connection tests
? checks for connection
1 passing (23ms)
如何讓 Mocha 在將測驗決議為通過之前等待 web 服務回傳資料?
uj5u.com熱心網友回復:
經過幾次試驗結束錯誤,我發現
- 當 Mocha 單元測驗需要等待某些東西時,它們必須回傳一個 Promise
- EventSource npm 包(它不是 100% 與原生 EventSource Javascript 物件兼容),出于某種原因,也許總是,也許只有在 Mocha 或其他什么中使用時,不呼叫
onmessage處理程式,所以你必須使用添加事件偵聽器替代addEventListener功能
這是我的作業代碼:
describe('SSE Protocol tests', () => {
it('checks for notifications on data changes', function () {
this.timeout(0);
return new Promise<boolean>((resolve, _reject) => {
var eventSourceInitDict = {https: {rejectUnauthorized: false}};
var source = new EventSource('http://localhost:3000/api/v1/prenotazione?subscribe=3600', eventSourceInitDict);
var count = 2;
source.addEventListener("results", function(event: any) {
const data = JSON.parse(event.data);
count--;
if(count == 0) {
resolve(true);
}
});
}).then(value => {
assert.equal(typeof(value), 'boolean');
assert.equal(value, true);
}, error => {
assert(false, error);
});
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493515.html
