Giter Site home page Giter Site logo

nimasoroush / differencify Goto Github PK

View Code? Open in Web Editor NEW
631.0 14.0 46.0 6.77 MB

Differencify is a library for visual regression testing

License: MIT License

JavaScript 94.18% Dockerfile 2.15% HTML 3.67%
visual-testing nodejs headless-chrome visual-regression-testing puppeteer jest

differencify's Introduction

Differencify
Differencify
Regression Testing suite!


CircleCI npm version Greenkeeper badge Mentioned in Awesome Jest

About

Differencify is a library for visual regression testing via comparing your local changes with reference screenshots of your website. It is built on top of chrome headless using Puppeteer.

Reference Local changes
Differencify Differencify

How it works

Differencify

Installation

Note: Differencify uses async/await and targets Node v7.6.0 or greater

Install the module:

npm install differencify

Usage

const Differencify = require('differencify');
const differencify = new Differencify(GlobalOptions);

Differencify matches Puppeteer's API completely. Look at API.md for more details.

Validate your changes

(async () => {
  const result = await differencify
    .init(TestOptions)
    .launch()
    .newPage()
    .setViewport({ width: 1600, height: 1200 })
    .goto('https://github.com/NimaSoroush/differencify')
    .waitFor(1000)
    .screenshot()
    .toMatchSnapshot()
    .result((result) => {
      console.log(result); // Prints true or false
    })
    .close()
    .end();

  // or unchained

  const target = differencify.init({ chain: false });
  await target.launch();
  const page = await target.newPage();
  await page.setViewport({ width: 1600, height: 1200 });
  await page.goto('https://github.com/NimaSoroush/differencify');
  await page.waitFor(1000);
  const image = await page.screenshot();
  const result = await target.toMatchSnapshot(image)
  await page.close();
  await target.close();

  console.log(result); // Prints true or false
})();

See more examples here

Usage with JEST

Only need to wrap your steps into it() function

const differencify = new Differencify();
describe('tests differencify', () => {
  it('validate github page appear correctly', async () => {
    await differencify
      .init()
      .launch()
      .newPage()
      .goto('https://github.com/NimaSoroush/differencify')
      .screenshot()
      .toMatchSnapshot()
      .close()
      .end();
  });
});

As you can see, you don't need to return result as toMatchSnapshot will automatically validate the result. See more jest examples here.

Test PASS

Test FAIL

Same way as Jest snapshots testing, to update the snapshots, run jest with --updateSnapshot or -u argument.

Jest reporter

You can generate an index document of the saved images by using the differencify jest reporter.

$ npm i -D differencify-jest-reporter

Enable the reporter in your jest config:

module.exports = {
  reporters: [
    'default', // keep the default reporter
    [
      'differencify-jest-reporter',
      {
        debug: true,
        reportPath: 'differencify_reports', // relative to root of project
        reportTypes: {
          html: 'index.html',
          json: 'index.json',
        },
      },
    ],
  ],
};

Alternatively, enable the reporter with the cli:

jest --reporters default differencify-jest-reporter

Jest reporter output

differencify-report

Usage with other test frameworks

If you are using other test frameworks you can still validate your tests. Differencify will return true or false by the end of execution. This can be used to assert on. See this example.

To Create/Update reference screenshots, simply set environment variable update=true and run the same code.

> update=true node test.js

Mocking browser requests

Differencify uses Mockeer to run chrome headless browser in isolation. This will help with more consistent and stable results when it comes dealing with a website that has inconsistent downstream dependencies. (e.g. unique API call returns different results based on request time). More details here

To use this feature call mockRequests during your tests.

(async () => {
  const result = await differencify
    .init(TestOptions)
    .launch()
    .newPage()
    .mockRequests()
    .goto('https://github.com/NimaSoroush/differencify')
    .screenshot()
    .toMatchSnapshot()
    .result((result) => {
      console.log(result);
    })
    .close()
    .end();

  // or unchained

  const target = differencify.init({ chain: false });
  await target.launch();
  const page = await target.newPage();
  await target.mockRequests();
  await page.goto('https://github.com/NimaSoroush/differencify');
  const image = await page.screenshot();
  const result = await target.toMatchSnapshot(image)
  await page.close();
  await target.close();

  console.log(result);
})();

More examples here

Debugging

It is possible to debug your tests execution by passing debug:true as global config in Differencify class. See full list of configs below

const differencify = new Differencify({ debug: true });

Visible mode

By default differencify runs chrome in headless mode. If you want to see the browser in non-headless mode set headless:false when launching the browser. See more details here.

const differencify = new Differencify();
(async () => {
  await differencify
    .init()
    .launch({ headless: false })
    .newPage()
    .goto('https://github.com/NimaSoroush/differencify')
    .screenshot()
    .toMatchSnapshot()
    .close()
    .end();
})();

API

See API.md for a full list of API calls and examples.

GlobalOptions

Parameter type required description default
debug boolean no Enables console output false
imageSnapshotPath string no Stores reference screenshots in this directory ./differencify_reports
saveDifferencifiedImage boolean no Save differencified image to test report path in case of mismatch true
saveCurrentImage boolean no Save the captured image from current test run to test report path true
mismatchThreshold number no Difference tolerance between reference/test image 0.001

TestOptions

Parameter type required description default
testName string no Unique name for your test case test
chain boolean no Whether to chain differencify commands or not. See API.md for more details true

Steps API

See API.md for a full list of API calls and examples.

Interested on Docker image!

A Docker base image is available for local and CI usage based on this Dockerfile. To see an example look at this Dockerfile.

Usage:

FROM nimasoroush/differencify
RUN npm install differencify
...

Links

See the integration test example for working usages and CI integration with jest, and mock examples in API.md

Visit project Gitter Chat for general Q/A around project

See CONTRIBUTING.md if you want to contribute.

Read this article that explain simple usage of this library

Article about how to use Differencify in Docker

Gist example with vanilla node

differencify's People

Contributors

artmann avatar danrr avatar dominicfraser avatar eransch avatar glentakahashi avatar greenkeeper[bot] avatar kamenb avatar ljpengelen avatar ll350 avatar newyork-anthonyng avatar nimasoroush avatar russellborja avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

differencify's Issues

Jest example needs update

It turns out I have to add these two methods to the test so the jest test can run successfully.
.launch()
.newPage()
or else I'm getting error:
: TypeError: Cannot read property 'goto' of null
at Target._handleFunc (/Users/jayhe/Desktop/jestDemo/node_modules/differencify/dist/target.js:111:50)

The successful jest test I'm using:
import Differencify from 'differencify';
const differencify = new Differencify({ debug: true });
describe('tests differencify', () => {
it('validate github page appear correctly', async () => {
await differencify
.init()
.launch()
.newPage()
.goto('https://github.com/NimaSoroush/differencify')
.screenshot()
.toMatchSnapshot()
.close()
.end();
});
});

Fail fast if url is not available

Currently differencify goes forward with steps and screenshots if the url is 404. It should fail fast if the url is not accessible in goto step

Adding Jest toMatchSnapshot support

Upgrading Differencify to support Jest Snapshot Testing.

differencify
      .init()
      .goto('https://github.com/NimaSoroush/differencify')
      .capture()
      .toMatchSnapshot()
      .close()
      .end();

toMatchSnapshot() would store and update captured image snapshot just as Jest do

Already running instance of headless Chrome makes tests fail

I'm getting test failures with

     Error: Failed to launch a browser.
         at Chromy.start$ (/node_modules/chromy/dist/index.js:147:21)
         at tryCatch (/node_modules/regenerator-runtime/runtime.js:65:40)
         at Generator.invoke [as _invoke] (/node_modules/regenerator-runtime/runtime.js:303:22)
         at Generator.prototype.(anonymous function) [as next] (/node_modules/regenerator-runtime/runtime.js:117:21)
         at tryCatch (/node_modules/regenerator-runtime/runtime.js:65:40)
         at invoke (/node_modules/regenerator-runtime/runtime.js:155:20)
         at /node_modules/regenerator-runtime/runtime.js:165:13

whenever I run the tests with an already running instance of headless Chrome. Killing that instance fixes the test.

Adding checks for free ports and fixing #9 will fix this.

How to get window object

Hi, is there any concrete example on how to get the window object? I need it for mocking but it is not working.

Differencify to save captured screenshots in each run alongwith producing diff screenshots

As of now, with differencify, we generate diff screenshots in "differencifiedoutput" folder.
If possible, we should introduce a flag , say saveScreenshots , which will save captured screenshots in each run. This saved screenshots will help to manually refer the diff clearly, if needed, in case of failure. Sometimes, when the **mismatchThreshold** is low , then it's difficult to make out the actual diff , by seeing the screenshot produced in "differencifiedoutput" folder. Default value can be made false for the flag saveScreenshots

Saving reference screenshot in particular directory issue

I am not able to save the reference screenshot in particular directory.
I want to save the screenshots in the 320x480 folder.
How can i acheive that?

`import Differencify from 'differencify'

const puppeteer = require('puppeteer')

const differencify = new Differencify({
debug: true,
imageSnapshotPath: './differencify_reports/320x480/',
})

export const liveScreenshot = (key, value, width1, height1) => {
return (async function takeLiveWebsiteSnapshot() {
try {
const target = differencify.init({
testName: value,
chain: false
})
await target.launch({ headless: true })
const page = await target.newPage()
await page.setViewport({
width: width1,
height: height1
})
await page.goto(key, { waitUntil: 'networkidle0' })
await page.content()
const bodyHandle = await page.$('body')
const { width, height } = await bodyHandle.boundingBox()
const screenshot = await page.screenshot({
clip: {
x: 0,
y: 0,
width,
height
}
})
const result = await target.toMatchSnapshot(screenshot)
await bodyHandle.dispose()
await expect(result).toEqual(true)
await console.log(result)
await target.close()
} catch (error) {
await console.log(error)
}
})()
}
`

Produce HTML report

Currently, Differencify outputs all images and the diffs, if any exist, to a folder. It could be made to produce a report as an HTML page that loads on test failure which shows what tests have failed, and the reference, output, and diff images.

Build artifacts in 1.4.0

@NimaSoroush It appears as though the 1.4.0 package doesn't have the latest build artifacts. Is it possible that it was published without npm run build occurring before hand?

Notice the differing function signatures between my build (left) and the tarball retrieved from NPM (right)

image

If this was a publishing mistake and not something on my end, I would recommend configuring a prepare NPM script such as:

  "prepare": "npm run build"

This will run before publishing as well as after an install from Github, it ensures that no matter how the package is pulled into a project it should have freshly built artifacts.

page.focus()

I'm having trouble getting puppetter to work - can anyone spot a problem with this test?

Thanks

import Differencify from '../index';

const differencify = new Differencify({ debug: true });

describe('Differencify', () => {
  beforeAll(async () => {
    await differencify.launchBrowser({ args: ['--no-sandbox', '--disable-setuid-sandbox'], headless: false });
  });
  afterAll(async () => {
    await differencify.cleanup();
  });
  it.only('simple', async () => {
    await differencify
      .init()
      .newPage()
      .setViewport({ width: 1024, height: 1024 })
      .goto('https://facebook.github.io/jest/docs/en/api.html')
      .page // tried without also
      .waitForSelector('footer')
      .focus('footer')
      .screenshot()
      .toMatchSnapshot()
      .close()
      .end();
  }, 20000);

Image comparison on SVGs is not consistent

While running comparisons locally and in docker and drone, I am seeing an animated svg always being different to a varying degree. Upping the threshold gets round the problem but is not ideal.

We ran locally with headless disable to check if the image was actually frozen so I would doubt that is the cause in docker/drone. It seems to be an issue of rendering the pixels a little differently each time.

Extremely slow in jest testing env

Why is it so slow in jest? You can also see it in the examples, which had to increase the testing timeout to be able to finish the test. Totally unusable :(

I tried to pinpoint it and it is the fs.readStream it looks like. I will investigate further later on. Just opened this issue as a reference.

Use path module to generate file paths

File paths are generated using concatenation in createDir, compareImage, saveImage. Probably worth changing to using path for better cross OS support.

Allow options for page.goto

It would be useful to pass options to the puppeteer page.goto method from the differencify goto method.

A very useful option is the waitUntil: 'networkidle' option.

In my particular case, it looks like chrome is not treating a link tag in the body as blocking so my visual test images are not being generated correctly. Using the waitUntil: 'networkidle' fixes this.

Match Differencify and Puppeteer API

Context:
From ms88privat's comment:

  • It would be hard for users to learn Differencify's API on top of Puppeteer API
  • It would be hard to keep Differencify's API up2date with Puppeteer's API

Goal:

  • Forward all method calls that are not matching Differencify's API interface directly to Puppeteer.
  • Differencify should be still able to override Puppeteer's API if it is necessary.
  • This should not introduce any breaking changes to difference's interface

CC: @ms88privat @badsyntax

Extend NodeEnvironment to avoid side effect methods

Based on jest-puppeteer-example it would be great to extend NodeEnvironment similar to this

for example, this will avoid differencify.launchBrowser() and differencify.cleanup() on this example

(async () => {
  await differencify.launchBrowser();
  const target = differencify.init({ testName: 'Differencify simple unchained', chain: false });
  const page = await target.newPage();
  await page.goto('https://github.com/NimaSoroush/differencify');
  await page.setViewport({ width: 1600, height: 1200 });
  await page.waitFor(1000);
  const image = await page.screenshot();
  const result = await target.toMatchSnapshot(image);
  await page.close();
  console.log(result) // True or False
  await differencify.cleanup();
})();

@xfumihiro: Anything to add?

Implications of returning more than a boolean following screenshot comparison?

Hey there!

First off, this project is awesome!

I've been exploring routes for building a screenshot/diff utility to provide interactive feedback based on mismatched screenshots. This was the first project I could see using, based on flexibility and overall performance.

In my implementation, it would be really helpful if the result returned following a call to toMatchSnapshot contained a path to the diff image. I forked and tested the change for my use case but wanted to share it here before proposing a PR, as I'm not sure if it impedes other use cases.

Below is my branch, I'm happy to incorporate feedback if this seems like a reasonable change.

https://github.com/Swingline0/differencify/tree/result-data (Diff)

Instead of a boolean, my change returns the actual result object so it looks more like this:

"result": {
    "diffPath": "[...]/Homepage 1.differencified.png",
    "matched": false
}

Thanks again for this awesome and inspiring work!

target.toMatchSnapshot() not behaving as expected

I was trying to do the following:

        const target = differencify.init({
          chain: false
        })
        await target.launch({ headless: true })
        const page = await target.newPage()
        await page.setViewport({
          width: 1366,
          height: 766
        })
        await page.goto(key, { waitUntil: 'networkidle0' })
        await page.content()
        const bodyHandle = await page.$('body')
        const { width, height } = await bodyHandle.boundingBox()
        await console.log(width, height)
        const imag = await fs.readFileSync(
          require.resolve('../../snapshots/' + value + '_screenshot.png')
        )
        const result = await target.toMatchSnapshot(imag)

Here( imag = local screenshot )and when im trying to match the reference screenshot with the(imag), the same local screenshot taken earlier is being saved as the present reference snapshot.

Possible to compare two different urls?

I'd like to compare my homepage in my test environment directly against the live environment

Is that possible with the current API?

e.g. something like:

it('ensures TEST vs PROD is expected', () => {
   const testHomepage = await page.goto('http://test.domain.com').screenshot();
   const prodHomepage = await page.goto('http://www.domain.com').screenshot();
    expect(
        await target.toMatchImageSnapshot(testHomepage, prodHomepage)
    ).toEqual(true)
})

Note: I realise this isn't strictly what differencify is designed for i.e. snapshot testing. I'm trying to replicate something like wraith "capture" mode.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.