node.js - 如何在 nodejs 中使用 jest 框架為 cassandra 的 execute 查詢編寫單元測試
我正在嘗試為我的代碼編寫單元測試案例,該代碼從 Cassandra 數據庫獲取活動/數據。我正在使用 Jest 框架進行單元測試。
const db = require('../../db/client');
getCampaigns(req: express.Request, res: express.Response) {
db.execute('select * from campaign_definitions', (err: any,
result: any) => {
if (err) {
logger.error(`${err.status || 500} - ${err.message} -
${req.originalUrl} - ${req.method} - ${req.ip}`);
return res.status(500).send(err);
}
res.send(result.rows);
});
}
我不知道如何使用 jest 為 'db.execute' 做 mock。我感謝你的幫助,謝謝
答案#1
你可以模擬 db.execute 使其不執行任何操作,並使用這個模擬來獲取傳遞給它的參數。
參數是查詢和回調,所以你只需要測試查詢是否正確以及回調是否按預期工作。
這裡有一個簡化的工作範例供你入門:
import * as express from 'express';
const db = require('../../db/client');
function getCampaigns(req: express.Request, res: express.Response) {
db.execute('select * from campaign_definitions', (err: any, result: any) => {
res.send(result.rows);
});
}
test('getCampaigns', () => {
const res: any = { send: jest.fn() };
const mock = jest.spyOn(db, 'execute'); // spy on db.execute...
mock.mockImplementation(() => {}); // <= ...and mock the implementation
getCampaigns({} as any, res);
const args = db.execute.mock.calls[0]; // <= get the args passed to db.execute
const query = args[0];
const callback = args[1];
callback(null, { rows: 'the rows' }); // <= call the callback
expect(query).toBe('select * from campaign_definitions'); // Success!
expect(res.send).toHaveBeenCalledWith('the rows'); // Success!
})
