我尝试了各种尝试。这是我最新的。我只是想对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)
);
});
});
我现在不知道如何进行这项工作。如果这会使事情变得更容易,我愿意尝试开玩笑。
这里是解决方法:
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