Unit testing, E2E testing, Karma, Protractor, Jasmine, Phantom.JS
Samuel Šramko
describe('1st tests', () => {
it('true is true', () => expect(true).toBe(true));
});it('matchers', () => {
const a = 12;
const message = "foo bar baz";
const b = {
foo: "foo"
};
expect(a.foo).toBeDefined();
expect(() => throw new TypeError("type error")).toThrowError("type error");
expect(true).toBe(true);
expect(true).not.toBe(false);
expect(a).toEqual(12);
expect(message).toMatch(/bar/);
expect(message).toContain("bar");
expect(b.foo).toBeDefined();
expect(null).toBeNull();
expect(3).toBeLessThan(4);
});
describe("A spy", () => {
var foo, bar = null, fetchedBar;
beforeEach(function() {
foo = {
setBar: (value) => bar = value,
getBar: () => bar
};
spyOn(foo, "setBar");
spyOn(foo, "getBar").and.returnValue(745);
foo.setBar(123);
foo.setBar(456, 'another param');
fetchedBar = foo.getBar();
});
it("spy matchers", () => {
expect(foo.setBar).toHaveBeenCalled();
expect(foo.setBar).toHaveBeenCalledTimes(2);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
expect(foo.setBar).toHaveBeenCalled();
expect(fetchedBar).toEqual(745);
});
});const webpackConfig = require('./webpack.test');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [
{pattern: './config/karma-test-shim.js', watched: false}
],
preprocessors: {
'./config/karma-test-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
};
config.set(_config);
};Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
var appContext = require.context('../src', true, /\.spec\.ts/);
appContext.keys().forEach(appContext);
var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(
browser.BrowserDynamicTestingModule,
browser.platformBrowserDynamicTesting());describe('CustomTextComponent (inline template)', () => {
let comp: CustomTextComponent;
let fixture: ComponentFixture<CustomTextComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ CustomTextComponent ],
});
fixture = TestBed.createComponent(CustomTextComponent);
comp = fixture.componentInstance; // CustomTextComponent test instance
// write all tests here
it('should ...', () => {});
});
});it('should display original title', () => {
fixture.detectChanges();
expect(comp.title).toBe('Title');
});
it('should display a different test title', () => {
comp.setTitle('Test Title');
fixture.detectChanges();
expect(comp.title).toBe('Test Title');
});TestBed.configureTestingModule({
declarations: [ CustomTextComponent ],
providers: [
{ provide: ComponentFixtureAutoDetect, useValue: true }
]
})const colorServiceStub = {
getColors: {colors: [], chartColors: []}, saveColors: {}
};
const notificationServiceStub = {
success: {}, error: {}
};
describe('colors component', () => {
let component: ColorsComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ColorsComponent],
providers: [
{provide: ColorService, useValue: colorServiceStub},
{provide: NotificationsService, useValue: notificationServiceStub}]
});
const fixture = TestBed.createComponent(ColorsComponent);
component = fixture.componentInstance;
});
it('should change color', () => {
const color = {value: '#123123'};
component.colorChanged('#aaaaaa', color);
expect(color.value).toBe('#aaaaaa');
});
});const colorServiceStub = {
getColors: {colors: [], chartColors: []}, saveColors: {}
};
const notificationServiceStub = {
success: {}, error: {}
};
describe('colors component', () => {
let component: ColorsComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ColorsComponent],
providers: [
{provide: ColorService, useValue: colorServiceStub},
{provide: NotificationsService, useValue: notificationServiceStub}]
});
const fixture = TestBed.createComponent(ColorsComponent);
const colorService = TestBed.get(ColorService);
const notificationService = fixture.debugElement.injector.get(NotificationsService);
});
});it('should show quote after getQuote promise (async)', async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => { // wait for async getQuote
fixture.detectChanges(); // update view with quote
expect(el.textContent).toBe(testQuote);
});
}));
it('should show quote after getQuote promise (fakeAsync)', fakeAsync(() => {
fixture.detectChanges();
tick(); // wait for async getQuote
fixture.detectChanges(); // update view with quote
expect(el.textContent).toBe(testQuote);
}));
it('should show quote after getQuote promise (done)', done => {
fixture.detectChanges();
spy.calls.mostRecent().returnValue.then(() => {
fixture.detectChanges(); // update view with quote
expect(el.textContent).toBe(testQuote);
done();
});
});exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['spec.js'],
multiCapabilities: [{
browserName: 'firefox'
}, {
browserName: 'chrome'
}]
}
describe('Protractor Demo App', () => {
it('should have a title', () => {
// browser is a protractor-created global variable
browser.get('http://juliemr.github.io/protractor-demo/');
expect(browser.getTitle()).toEqual('Super Calculator');
});
});// spec.js
describe('Protractor Demo App', function() {
it('should add one and two', function() {
browser.get('http://juliemr.github.io/protractor-demo/');
element(by.css('first-input')).sendKeys(1);
element(by.css('second-input')).sendKeys(2);
element(by.id('gobutton')).click();
});
});var phantom = require('phantom'), fs = require('fs'), q = require('q'),
os = require('os'), argv = require('minimist')(process.argv.slice(2)),
pageProperties = {width: 1920, height: 1080};
var loginPage, ph;
var hostname = os.hostname();
var baseUrl = 'http://' + hostname + '/#/';
(async () => {
const ph = await phantom.create(['--web-security=no',
'--ignore-ssl-errors=yes', '--webdriver-loglevel=NONE']);
const page = await ph.createPage();
await page.property('viewportSize', pageProperties);
const status = await page.open(baseUrl);
if (status !== 'success') {
throw new Error('open page failed');
}
await page.evaluate((login, password) => {
document.getElementById("username").value = login;
document.getElementById("password").value = password;
document.getElementsByName("submit")[0].click();
}, "admin", "admin");
}
setTimeout(() => {
page.render(outputFileName);
ph.exit(0);
}, 5000);
})();