Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snapshot testing on Angular 1.x with Jest

I'd like to use Jest to snapshot-test my angular 1.x directives. I've already got a working test environment with jest, but I'm not sure how (and if I can) snapshot test my directives/components.

I don't think I can use the renderer object used in this example (looks like a react-specific object) http://facebook.github.io/jest/docs/en/snapshot-testing.html#content and I'm not sure how to use the .toJSON() function in order to serialize my directive/components.

This is the only link I've found on Jest+Angular 1.x usage: https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251 and I can't find any answer about snapshot testing.

Thanks in advance,

Federico

like image 925
Federico Rota Avatar asked Jan 19 '26 10:01

Federico Rota


1 Answers

It works.

test.js

const angular = require('angular');
require('angular-mocks');

describe('Renderer', () => {
  let element;
  let scope;

  beforeEach(
    angular.mock.inject(($rootScope, $compile) => {
      scope = $rootScope.$new();
      element = $compile(
        '<div><label ng-show="label.show">1</label><label ng-hide="label.show">2</label></div>'
      )(scope);
      scope.$digest();
    })
  );

  it('should render the element', () => {
    expect(element).toBeDefined();
    expect(element[0]).toMatchSnapshot();
  });
});

Snapshot

exports[`Renderer should render the element 1`] = `
<div
  class="ng-scope"
>
  <label
    class="ng-hide"
    ng-show="label.show"
  >
    1
  </label>
  <label
    ng-hide="label.show"
  >
    2
  </label>
</div>
`;
like image 63
Tobias Timm Avatar answered Jan 21 '26 03:01

Tobias Timm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!