Утверждение / ожидание в Mocha / Chai не работает, чтобы отловить ошибки броска в конструкторе - PullRequest
1 голос
/ 10 января 2020

У меня есть класс, который в буфере принимает конструктор, подобный этому

export class ZippedFileBlaBla {
  zip: AdmZip;
  constructor(zipData: Buffer) {
    try {
      this.zip = new AdmZip(zipData);
    } catch (err) {
      throw new ZipDecompressionError(`Invalid ZIP file, error: ${err}`);
    }
  }
}

Я хотел бы протестировать этот класс, но я могу сделать это, не используя ни Mocha, ни Chai. Мой тест пока что

// this does not work
expect(() => new ZippedFileBlaBla(bufferOfInvalidFile)).to.throw(Error)

// this also does not work
assert.throws(function () {new ZippedFileBlaBla(bufferOfInvalidFile)}, Error)

Хотя, конечно, когда я запускаю модульные тесты, выдается ошибка, и я вижу ее в консоли ...

Буду признателен за любые советы о том, что Я делаю не так здесь

1 Ответ

0 голосов
/ 13 января 2020

Вы должны использовать заглушку или макет библиотеки, чтобы заглушить или насмехаться над классом 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

...