import { checkBatchForError, ERROR_MESSAGE_TIP } from "./error";
import { EnoFactory } from "./EnoFactory";
import { of } from "rxjs";
import { tap, delay } from "rxjs/operators";
import { get } from "lodash";

describe("checkBatchForError", () => {
  it("should find an error and throw", () => {
    const enoFactory = new EnoFactory("error");
    enoFactory.setSecurity("security/policy/local");
    enoFactory.setField("error/message/tip", ["some/error/tip"]);
    const errorEno = enoFactory.makeEno();
    expect(() => checkBatchForError([errorEno])).toThrowError(
      JSON.stringify(errorEno)
    );
  });

  it("should find an error and error an Observable", (done) => {
    const enoFactory = new EnoFactory("error");
    enoFactory.setWellKnownTip("my-error-tip");
    enoFactory.setSecurity("security/policy/local");
    enoFactory.setField("error/message/tip", ["some/error/tip"]);
    const errorEno = enoFactory.makeEno();

    of([errorEno])
      .pipe(delay(1), tap(checkBatchForError))
      .toPromise()
      .then(fail)
      .catch((err) => {
        const errEno = JSON.parse(err.message);
        expect(errEno.tip).toBe("my-error-tip");
      })
      .finally(done);
  });

  it("should not find an error and throw", () => {
    expect(() => checkBatchForError([])).not.toThrow();
  });

  it("should not throw an error and if skippedError is provided", () => {
    const enoFactory = new EnoFactory("error");
    enoFactory.setSecurity("security/policy/local");
    enoFactory.setField("error/message/tip", [ERROR_MESSAGE_TIP.NOT_FOUND]);
    expect(() =>
      checkBatchForError([enoFactory.makeEno()], [ERROR_MESSAGE_TIP.NOT_FOUND])
    ).not.toThrow();
  });

  it("should still throw an error with skippedError provided", () => {
    const enoFactory1 = new EnoFactory("error");
    enoFactory1.setSecurity("security/policy/local");
    enoFactory1.setField("error/message/tip", [ERROR_MESSAGE_TIP.NOT_FOUND]);
    const notFoundEno = enoFactory1.makeEno();
    const enoFactory = new EnoFactory("error");
    enoFactory.setSecurity("security/policy/local");
    enoFactory.setField("error/message/tip", ["some/error/tip"]);
    const errorEno = enoFactory.makeEno();
    expect(() =>
      checkBatchForError([notFoundEno, errorEno], [ERROR_MESSAGE_TIP.NOT_FOUND])
    ).toThrowError(JSON.stringify(errorEno));
  });
});
