gpt4 book ai didi

javascript - 如何在自定义函数中模拟 Axios?

转载 作者:行者123 更新时间:2023-12-04 08:36:34 28 4
gpt4 key购买 nike


我该如何模拟 axios.get()当它在我自己的自定义函数中时?
在这一点上我完全迷失了。希望有人能看到我做错了什么。
细节
我有以下 getString()从网站下载 html 并返回值 > 0 的函数如果找到字符串并且 -1如果未找到字符串。
getString()用途 axios.get()要下载 html,我想 Jest 模拟这个调用。
This article是我能找到的最接近我的情况的,但在他的情况下,他 mock 了一个独立的 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'
}),
}
});
包.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在您的依赖项中,如果不是 - 安装它

yarn add --dev jest || npm i -D jest
然后通过模拟 axios 来测试您的实现而不是您要测试的实现。
其余的 getString可能看起来像这样
const axios = require('axios');
const getString = require('./getString');

jest.mock('axios')

const mockResponseData = {
hello: "world"
}

describe('getString', () => {
describe('axios returning resolved promise', () => {
beforeAll(() => {
// returning transformed mock
axios.get.mockResolvedValue({
data: mockResponseData
})
})

describe('called with arguments', () => {
let result
beforeAll(() => {
result = getString({
url: 'http://localhost',
string: 'If you are the website administrator',
timeout: 1000,
maxRedirects: 0
})
})

it('should call axios.get', async () => {
await result
expect(axios.get).toHaveBeenCalledWith(
"http://localhost",
{
"maxRedirects": 0,
"timeout": 1000,
"transformResponse": [
expect.any(Function)
],
"validateStatus": null
}
)
})

it('should return the response.data', async () => {
expect(await result).toEqual(mockResponseData)
})
})
})

describe('axios returning rejected promise', () => {
beforeAll(() => {
// returning transformed mock
axios.get.mockRejectedValue({
data: mockResponseData
})
})

describe('called with arguments', () => {
let result
beforeAll(() => {
result = getString({
url: 'http://localhost',
string: 'If you are the website administrator',
timeout: 1000,
maxRedirects: 0
})
})

it('should return -1', async () => {
expect(await result).toEqual(-1)
})
})
})
})
编辑:为了达到 100% 的覆盖率,您还必须测试您的实现 transformResponse为了做到这一点,你可以像这样模拟实现
// this is not tested
import mockResponseBody from './localMock.json';

axios.get.mockImplementation((url, { transformResponse }) =>
Promise.resolve({
data: transformResponse.reduce((acc, fn) => fn(acc), mockResponseData)
})
)


working example

关于javascript - 如何在自定义函数中模拟 Axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64767605/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com