【发布时间】:2021-02-22 07:33:13
【问题描述】:
问题
当axios.get() 在我自己的自定义函数中时,如何模拟它?
此时我完全迷失了。希望有人能看到我做错了什么。
详情
我有下面的 getString() 函数,它从网站下载 html,如果找到字符串,则返回值 > 0,如果找不到字符串,则返回 -1。
由于getString() 使用axios.get() 下载html,我想开玩笑地模拟这个调用。
This article 是我能找到的最接近我的情况,但在他的情况下,他模拟了一个独立的axios.request(),其中我的axios.get() 在我的自定义getString() 中。
我的尝试是这样的:
getString.test.js
const axios = require('axios');
const getString = require('./getString');
jest.mock('./getString', () => {
return {
baseURL: 'localhost',
get: jest.fn().mockResolvedValue({
data: 'xxx If you are the website administrator xxx'
}),
}
});
packages.json
{
"name": "jest",
"version": "1.0.0",
"description": "",
"main": "getString.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC"
}
我已经完成了npm init -y && npm install --save-dev jest,但是npm run test 给了我
$ npm run test
> jest@1.0.0 test /home/mje/projects/jest
> jest
sh: jest: command not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! jest@1.0.0 test: `jest`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the jest@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
简单的 PoC 来自 the docs。
index.js
const getString = require('./getString');
(async function(){
'use strict'
const isOk = await getString({
url: 'http://localhost',
string: 'If you are the website administrator',
timeout: 1000,
maxRedirects: 0
});
console.log(isOk);
})();
getString.js
const axios = require('axios');
const qs = require('qs');
module.exports = async (options) => {
options = options || {};
options.url = options.url || {};
options.string = options.string || null;
options.timeout = options.timeout || 1000;
options.maxRedirects = options.maxRedirects || 0;
try {
const response = await axios.get(options.url, {
timeout: options.timeout,
maxRedirects: options.maxRedirects,
validateStatus: null,
transformResponse: [function (data) {
return data.search(options.string);
}]
});
return await response.data;
} catch (error) {
return -1;
}
};
【问题讨论】:
-
你是否安装了
jest作为依赖项?
标签: javascript node.js ecmascript-6 axios jestjs