chai-image

Build Status Semantic Release enabled Renovate enabled MIT license

画像に関するアサーションを使用してチャイを拡張する

expect(bufImage).to.matchImage(bufExpectedImage);

Example

期待される 実際の
Expected Image Actual Image
差分(左上揃え) 差分(中央揃え)
Diff Image Diff Image

この場合、matchImage アサーションは失敗します。

使用法

chai-image をインストールして、すぐに使い始めましょう。

$ npm install chai-image --save-dev

以下に

import * as chai from "chai";
import { chaiImage } from "chai-image";

chai.use(chaiImage);

// Then either:
const expect = chai.expect;
// or:
const assert = chai.assert;
// or:
chai.should();
// according to your preference of assertion style

アサーション

matchImage(expected: Buffer, options?: MatchImageOptions)

注: 現在、PNG 画像形式のみがサポートされています。

// Simple Example
import * as fs from "fs";

const bufActual = fs.readFileSync("actual.png");
const bufExpected = fs.readFileSync("expected.png");

expect(bufActual).to.matchImage(bufExpected);
// Real-world Example
import * as sharp from "sharp";

class ImageService {
  public async transform(buf: Buffer): Promise<Buffer> {
    return await sharp(buf).resize().max(320, 320).png().toBuffer();
  }
}

const service = new ImageService();

describe("ImageService", () => {
  describe("#transform", () => {
    it("should transform image", async () => {
      const input = fs.readFileSync("fixtures/input.png");
      const output = fs.readFileSync("fixtures/output.png");
      
      expect(await service.transform(input)).to.matchImage(output);
    });
  });
});

画像が与えられた画像と一致するかどうかをテストします。

画像の比較は pixelmatch ライブラリによって処理されます。出力設定が提供されている場合、chai-image は差分結果を表示するためにいくつかのファイルを作成します。


enum Align {
  LEFT_TOP = "leftTop",
  CENTER = "center",
}

interface MatchImageOptions {
  // Custom diff config passed to pixelmatch
  diff?: DiffOptions;
  
  // Image aligning config for aligning different size image (default: Align.LEFT_TOP)
  align?: Align;
  
  // Output config
  // if specified, chai-image will create output files to visualize diff 
  output?: OutputOptions;
}

interface DiffOptions {
  threshold?: number;
  includeAA?: boolean;
  alpha?: number;
  aaColor?: [number, number, number];
  /* The color of differing pixels in the diff output. [255, 0, 0] by default. */
  diffColor?: [number, number, number];
}

interface OutputOptions {
  // Currently name is used to generate filename
  name: string;
  // Path of output directory (default: WORKDING_DIR/outputs)
  dir?: string;
  
  // Output creation conditions
  // Controls when to create output files (default: failure)
  on?: "failure" | "always";
  
  // Controls output file types (default: false)
  diffOnly?: boolean;
}

変更履歴

CHANGELOG を参照してください。

テスト

$ npm run test

構築

$ npm run build

ライセンス

MIT

完全なライセンスは mooyoul.mit-license.org で参照できます。