Вы должны использовать заглушку или макет библиотеки, чтобы заглушить или насмехаться над классом AdmZip
. Так что вы можете контролировать процесс создания класса AdmZip
с ошибкой или нет.
Например
index.ts
import { AdmZip } from "./admZip";
import { ZipDecompressionError } from "./zipDecompressionError";
export class ZippedFileBlaBla {
zip: AdmZip;
constructor(zipData: Buffer) {
try {
this.zip = new AdmZip(zipData);
} catch (err) {
throw new ZipDecompressionError(`Invalid ZIP file, error: ${err}`);
}
}
}
admZip.ts
:
export class AdmZip {
constructor(zipData: Buffer) {}
}
zipDecompressionError.ts
:
export class ZipDecompressionError extends Error {
constructor(msg: string) {
super(msg);
}
}
index.test.ts
:
import { ZippedFileBlaBla } from "./";
import * as admZip from "./admZip";
import sinon from "sinon";
import { expect } from "chai";
describe("59686738", () => {
afterEach(() => {
sinon.restore();
});
it("should throw zip decompression error", () => {
const AdmZipStub = sinon.stub(admZip, "AdmZip").callsFake(() => {
throw new Error("some error");
});
const bufferOfInvalidFile = Buffer.from([1]);
expect(() => new ZippedFileBlaBla(bufferOfInvalidFile)).to.throw(Error);
sinon.assert.calledWithExactly(AdmZipStub, bufferOfInvalidFile);
});
it("should create adm zip", () => {
const mZip = {};
const AdmZipStub = sinon.stub(admZip, "AdmZip").callsFake(() => mZip);
const bufferOfInvalidFile = Buffer.from([1]);
const instance = new ZippedFileBlaBla(bufferOfInvalidFile);
expect(instance.zip).to.be.eql(mZip);
sinon.assert.calledWithExactly(AdmZipStub, bufferOfInvalidFile);
});
});
Результаты модульных испытаний с отчетом о покрытии:
59686738
✓ should throw zip decompression error
✓ should create adm zip
2 passing (10ms)
--------------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 50 | 92.31 | 100 | |
admZip.ts | 100 | 100 | 50 | 100 | |
index.test.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
zipDecompressionError.ts | 100 | 50 | 100 | 100 | 3 |
--------------------------|----------|----------|----------|----------|-------------------|
Источник код: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59686738