当想要对启动http请求并获取数据的函数进行单元测试时,我遇到了问题。请求被截获但该函数没有收到我在nock函数的.reply()子句中定义的内容。我一直在苦苦挣扎几个小时,没有任何关于问题所在的线索!
这是我的功能:
import request from 'request';
import { pick, map } from 'lodash';
import { logger, getEnv } from './utils';
export default function getStoresFromProductDB() {
const dataToPick = [
'iccli',
'store_name',
];
const host = 'http://localhost:4001';
const url = `${host}/store`;
logger.info(`Getting stores from product DB at URL ${url}`);
return new Promise((resolve, reject) => {
request(url, { json: true }, (err, res, body) => {
if (err) {
reject(err);
} else {
const { data } = body;
resolve(map(data, store => pick(store, dataToPick)));
}
});
});
}
这是我的测试代码:
describe('Testing getting stores from product database', () => {
it('should return 200 and the list of available stores from product database', async () => {
nock('http://localhost:4001')
.get('/store')
.reply(200, stores);
const data = await getStoresFromProductDB();
console.log('data', data);
});
});
你能帮我吗?
答案 0 :(得分:1)
所以测试代码必须是这样的:
describe('Testing getting stores from product database', () => {
it('should return 200 and the list of available stores from product database', async () => {
nock('http://localhost:4001')
.get('/store')
.reply(200, { data: stores });
const data = await getStoresFromProductDB();
console.log('data', data);
});
});