question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to include jasmine?

See original GitHub issue

I am using jasmine.createSpyObj() in my tests/examples. But this results in an error in UI-Jar.

__ui-jar-temp-module-689e6bd400733cf8e738d027a2ab7e31.js:19 Uncaught ReferenceError: jasmine is not defined

What do I need to change to make jasmine available?

Here is an example to reproduce the issue:

test.service.ts

import { Injectable } from '@angular/core';
import { Observable, of } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class TestService {

  constructor(
  ) {
  }

  getSomething(): Observable<any> {
    return of('something');
  }
}

test.component.ts

import { Component, OnInit } from '@angular/core';
import { TestService } from "./test.service";
/**
 * @group Test
 * @component TestWithJasmine
 */
@Component({
  selector: 'jui-jar-test',
  template: `template`
})
export class TestComponent implements OnInit {

  constructor(
    private testService: TestService
  ) {

  }

  ngOnInit(
  ) {
    this.testService.getSomething();
  }
}

test.component.spec.ts

import { async, TestBed } from "@angular/core/testing";
import { of } from "rxjs";

import { TestComponent } from "./test.component";
import { TestService } from "./test.service";


describe('TestComponent', () => {
  let serviceSpy: jasmine.SpyObj<TestService>;

  beforeEach(async(() => {
    /**
     * @uijar TestComponent
     */
    TestBed.configureTestingModule({
      declarations: [TestComponent],
      providers: [
        TestComponent,
        {
          provide: TestService,
          useValue: jasmine.createSpyObj('TestService', ['getSomething'])
        }
      ]
    })
      .compileComponents();

    serviceSpy = TestBed.get(TestService);
    serviceSpy.getSomething.and.callFake(
      () => {
        return of('success');
      }
    );
  }));

  /**
   * @uijarexample Trigger jasmine error
   */
  it(
    'should show test component',
    () => {
      const fixture = TestBed.createComponent(TestComponent);
      fixture.detectChanges();
    }
  );
});

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
ThomasWeinertcommented, Mar 14, 2019

I got a step further by creating my own jasmine boot script and including it into polyfill.ts:

(function() {
  var jasmineRequire = require('jasmine-core/lib/jasmine-core/jasmine');
  window.jasmine = jasmineRequire.core(jasmineRequire);
  var env = jasmine.getEnv();
  var jasmineInterface = jasmineRequire.interface(jasmine, env);
  extend(window, jasmineInterface);

  function extend(destination, source) {
    for (var property in source) destination[property] = source[property];
    return destination;
  }
}());

Now jasmine.createSpyObj() is available and works. I modified the test component to use the mock.

test.component.ts

import { Component, OnInit } from '@angular/core';
import { TestService } from "./test.service";

/**
 * @group Test
 * @component TestWithJasmine
 */
@Component({
  selector: 'jui-jar-test',
  template: `<div class="result">{{testResult}}</div>`
})
export class TestComponent implements OnInit {

  testResult = 'fail';

  constructor(
    private testService: TestService
  ) {}

  ngOnInit() {
    this.testService.getSomething().subscribe(
      (result) => {
        this.testResult = result;
      }
    );
  }
}

Using the HTTPClient example from the readme I modified the spec file to provide it. It works fine in Karma, but the mock method is never initialized in UI-Jar.

``ERROR TypeError: Cannot read property ‘subscribe’ of undefined`

test.component.spec.ts

import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { of } from "rxjs";

import { TestComponent } from "./test.component";
import { TestService } from "./test.service";

describe('TestComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let serviceSpy: jasmine.SpyObj<TestService>;

  beforeEach(async(() => {
    /**
     * @uijar TestComponent
     */
    TestBed.configureTestingModule(
      {
        declarations: [TestComponent],
        providers: [
          TestComponent,
          {
            provide: TestService,
            useValue: jasmine.createSpyObj('TestService', ['getSomething'])
          }
        ]
      }
    ).compileComponents().then(
      () => {
        fixture = TestBed.createComponent(TestComponent);
        serviceSpy = TestBed.get(TestService);
        serviceSpy.getSomething.and.callFake(
          () => {
            return of('success');
          }
        );
       fixture.detectChanges();
      }
    );
  }));

  /**
   * @uijarexample Show component with data from service   
   */
  it(
    'should show test component',
    () => {
      const element = fixture.debugElement.query(By.css('div.result')).nativeElement;
      expect(element.textContent.trim()).toBe('success');
    }
  );
});

Any suggestion how the spec file should look for UI-Jar?

0reactions
mveer-agarwalcommented, Jun 9, 2020

I have added the below mentioned code with my polyfills but running UI-Jar test is still giving exception.

declare global {
	interface Window {
		jasmine: any;
	}
}

window.jasmine = window.jasmine || {};
(function() {

	const jasmineRequire = require('jasmine-core/lib/jasmine-core/jasmine');
	window.jasmine = jasmineRequire.core(jasmineRequire);
	const env = window.jasmine.getEnv();
	const jasmineInterface = jasmineRequire.interface(window.jasmine, env);
	extend(window, jasmineInterface);

	function extend(destination: any, source: any) {
		for (const property in source) {
			if (property) {
				destination[property] = source[property];
			}
		}
		return destination;
	}
}());

Capture

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting Started - Jasmine Documentation
Jasmine for Node.js. Add Jasmine to your package.json npm install --save-dev jasmine. Initialize Jasmine in your project npx jasmine init.
Read more >
An Introduction to Jasmine Unit Testing - freeCodeCamp
Jasmine is the most popular JS library for unit testing web apps. In this tutorial, designed for beginners, we'll present you with a...
Read more >
Jasmine Framework Tutorial: Unit Testing with Example
To run the test, you need to execute the jasmine command. This will find all files which have the 'spec' word attached to...
Read more >
Jasmine unit testing tutorial with examples - HowToDoInJava
Jasmine is one of the popular JavaScript unit testing frameworks which is capable of testing synchronous and asynchronous JavaScript code.
Read more >
Jasmine cheatsheet - Devhints
Note: This cheatsheet may be a little outdated. Also see the Jest cheatsheet. Jest uses Jasmine, and therefore has similar API. Expectations. expect( ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found