gpt4 book ai didi

javascript - 使用 HTML 夹具 stub Axios Get 请求

转载 作者:行者123 更新时间:2023-12-02 22:15:02 30 4
gpt4 key购买 nike

我尝试过各种尝试。这是我最新的。我只是想 stub Axios 请求并返回固定装置。

const { expect } = require('chai');
const sinon = require('sinon');
const { readFile } = require('fs');
const axios = require('axios');

let htmlFixture;

const htmlFixtureData = readFile(
'./test/fixtures/htmlFixture.html',
(err, file) => {
if (err) throw err;
htmlFixture(file);
}
);

复制一些 Axios 响应对象。

htmlFixture = (data) => ({
status: 200,
statusText: 'OK',
headers: {},
data
});

const { getTextBody } = require('../src/app');

describe('Get text body', () => {
let sandbox = sinon.createSandbox();
beforeEach(() => (sandbox = sinon.createSandbox()));
afterEach(() => (sandbox = sandbox.restore()));

it('should return the text body from the html website', () => {
sandbox.stub(axios, 'get').resolves(htmlFixtureData);
console.log(htmlFixture, '< --- fixture here');
expect(
getTextBody('http://www.fake-website.com/').to.equal(htmlFixtureData)
);
});
});

我现在不知道如何进行这项工作。如果这能让事情变得更容易的话,我愿意尝试 Jest。

最佳答案

解决方案如下:

app.js:

const axios = require("axios");

function getTextBody(url) {
return axios.get(url);
}

module.exports = { getTextBody };

app.test.js:

const { expect } = require("chai");
const sinon = require("sinon");
const { readFileSync } = require("fs");
const path = require("path");
const axios = require("axios");

const htmlFixtureData = readFileSync(path.resolve(__dirname, "./test/fixtures/htmlFixture.html")).toString();

const { getTextBody } = require("./app");

describe("Get text body", () => {
let sandbox = sinon.createSandbox();
beforeEach(() => (sandbox = sinon.createSandbox()));
afterEach(() => (sandbox = sandbox.restore()));

it("should return the text body from the html website", async () => {
sandbox.stub(axios, "get").resolves(htmlFixtureData);
const actual = await getTextBody("http://www.fake-website.com/");
expect(actual).to.be.equal(htmlFixtureData);
sandbox.assert.calledWith(axios.get, "http://www.fake-website.com/");
});
});

带有覆盖率报告的单元测试结果:

 Get text body
✓ should return the text body from the html website


1 passing (9ms)

-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
app.js | 100 | 100 | 100 | 100 | |
app.test.js | 100 | 100 | 100 | 100 | |
-------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59418138

关于javascript - 使用 HTML 夹具 stub Axios Get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59418138/

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