Skip to content

Hybrid unit testing. #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.cjs",
"assets": [
"app/img",
"app/phones",
Expand All @@ -109,8 +110,7 @@
"app/app.animations.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"build-webpack-ngJs/ngJsScripts.bundle.min.js"
"node_modules/jquery/dist/jquery.js"
]
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Currently, using the directives that extend UpgradeComponent, we can only test component creation.

import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';

import {Phone, PhoneData} from '../../services/phone.service';

import { PhoneListComponentWrapper } from './phone-list.component.wrapper';
import {UpgradeModule } from '@angular/upgrade/static';

class MockPhone {
queryByPromise(): Promise<PhoneData[] | undefined> {
let mockList = [
{name: 'Nexus S', snippet: '', images: [], age: 1},
{name: 'Motorola DROID', snippet: '', images: [], age: 2}
];

return new Promise((resolve) => {
resolve(mockList);
})
}
}

@Component({
template: `<phone-list></phone-list>`
})
class MockPhoneListComponent { }

let fixture: ComponentFixture<MockPhoneListComponent>;

describe('PhoneList', () => {

beforeEach(waitForAsync(() => {
TestBed
.configureTestingModule({
declarations: [
PhoneListComponentWrapper,
MockPhoneListComponent
],
providers: [
{provide: Phone, useClass: MockPhone},
{provide: '$scope', useExisting: '$rootScope'}
],
imports: [
UpgradeModule
]
})
.compileComponents();

// Bootstrap Angular JS
TestBed.inject(UpgradeModule).bootstrap(document.documentElement, ['phonecatApp']);
}));

beforeEach(() => {
fixture = TestBed.createComponent(MockPhoneListComponent);
fixture.detectChanges(); // Trigger initial data binding
});

it('should create a component', () => {
expect(fixture).toBeTruthy();
const component = fixture.componentInstance;
expect(component).toBeTruthy();
});
});
8 changes: 8 additions & 0 deletions app/angular-area/services/phone.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ export class Phone {
get(id: string): Observable<PhoneData> {
return this.http.get<PhoneData>(`phones/${id}.json`);
}

queryByPromise(): Promise<PhoneData[] | undefined> {
return this.query().toPromise();
}

getByPromise(id: string): Promise<PhoneData | undefined> {
return this.get(id).toPromise();
}
}

angular.module('core.phone')
Expand Down
3 changes: 2 additions & 1 deletion app/phone-list/phone-list.component.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ angular.
template: `<ng-include src="'phone-list/phone-list.template.html'"></ng-include>`,
controller: ['phone',
function PhoneListController(phone) {
phone.query().subscribe(phones => {
this.phones = [];
phone.queryByPromise().then(phones => {
this.phones = phones;
});
this.orderProp = 'age';
Expand Down
37 changes: 29 additions & 8 deletions app/phone-list/phone-list.component.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,61 @@ describe('phoneList', function() {

// Test the controller
describe('PhoneListController', function() {
var $httpBackend, ctrl, mockPhoneService, $http, $q;

// Due to upgrading the phone service to angular,
// the mock component initialization is not working because of unexpected provider-related errors.
/*
var $httpBackend, ctrl;
// Create an empty object to mock the phone service and inject it into the provider.
// We'll implement the mock service later because we should't inject anything
// before injecting this mock service in the mock module.
// Otherwise, we'll get "Error: Injector already created, can not register a module!".
beforeEach(function() {
mockPhoneService = {
queryByPromise: function() {}
};

beforeEach(inject(function($componentController, _$httpBackend_) {
angular.mock.module(function($provide) {
$provide.value("phone", mockPhoneService);
})
});

beforeEach(inject(function($componentController, _$q_, _$http_, _$httpBackend_) {
$q = _$q_;
$http = _$http_;
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('phones/phones.json')
.respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);

// Implement mock query of the mock service here.
mockPhoneService.queryByPromise = function() {
var deferred = $q.defer();
$http.get('phones/phones.json')
.then(function(response) {
deferred.resolve(response.data);
});
return deferred.promise;
};

ctrl = $componentController('phoneList');
}));

it('should create a `phones` property with 2 phones fetched with `$http`', function() {
jasmine.addCustomEqualityTester(angular.equals);

expect(ctrl.phones).toEqual([]);

$httpBackend.flush();
expect(ctrl.phones).toEqual([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
});

it('should set a default value for the `orderProp` property', function() {
expect(ctrl.orderProp).toBe('age');
});
*/

// Minimal test to verify if the test runner is working.
it('should subtract', function() {
var a = 3, b = 7;
var sub = a - b;
expect(sub).toEqual(-4);
});

});

});
2 changes: 1 addition & 1 deletion build-webpack-ngJs/ngJsScripts.bundle.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/angularjs-phonecat-to-angular/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
<div ng-view class="view-frame"></div>
</div>

<script src="runtime.9c04bd24e47ac341.js" type="module"></script><script src="polyfills.f5e663f919440dc5.js" type="module"></script><script src="scripts.3b643bbe4b5e8993.js" defer></script><script src="main.7b26605e243c4fcf.js" type="module"></script></body>
<script src="runtime.9c04bd24e47ac341.js" type="module"></script><script src="polyfills.f5e663f919440dc5.js" type="module"></script><script src="scripts.2db18f04beaedee2.js" defer></script><script src="main.71a8ff9d0f7a71d5.js" type="module"></script></body>
</html>

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 49 additions & 0 deletions karma.angularJS.conf.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//jshint strict: false
module.exports = function(config) {
config.set({

basePath: './app',

files: [
'lib/angular/angular.js',
'lib/angular-animate/angular-animate.js',
'lib/angular-resource/angular-resource.js',
'lib/angular-route/angular-route.js',
'../node_modules/angular-mocks/angular-mocks.js',
'**/*.module.*js',
'**/*.service.*js',
'*!(.module|.spec).js',
'!(lib)/**/*!(.module|.spec).js',
'**/*.spec.js',
],

autoWatch: true,

frameworks: ['jasmine'],

browsers: ['Chrome'],

plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-webpack',
],

webpack: {
// karma watches the test entry points
// Do NOT specify the entry option
// webpack watches dependencies

// webpack configuration
"mode": "development",
},

preprocessors: {
// process your `esmodule` syntax of your files
'**/*.js': ['webpack'],
'**/*.spec.js': ['webpack']
},

});
};
74 changes: 25 additions & 49 deletions karma.conf.cjs
Original file line number Diff line number Diff line change
@@ -1,49 +1,25 @@
//jshint strict: false
module.exports = function(config) {
config.set({

basePath: './app',

files: [
'lib/angular/angular.js',
'lib/angular-animate/angular-animate.js',
'lib/angular-resource/angular-resource.js',
'lib/angular-route/angular-route.js',
'../node_modules/angular-mocks/angular-mocks.js',
'**/*.module.*js',
'**/*.service.*js',
'*!(.module|.spec).js',
'!(lib)/**/*!(.module|.spec).js',
'**/*.spec.js',
],

autoWatch: true,

frameworks: ['jasmine'],

browsers: ['Chrome'],

plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-webpack',
],

webpack: {
// karma watches the test entry points
// Do NOT specify the entry option
// webpack watches dependencies

// webpack configuration
"mode": "development",
},

preprocessors: {
// process your `esmodule` syntax of your files
'**/*.js': ['webpack'],
'**/*.spec.js': ['webpack']
},

});
};
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
files: [
'build-webpack-ngJs/ngJsScripts.bundle.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/**/*.spec.js'
],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
browsers: ['Chrome'],
restartOnFileChange: true
});
};

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@
"preupdate-webdriver": "npm install",
"protractor": "protractor e2e-tests/protractor.conf.cjs",
"start-http-server": "http-server ./ -a localhost -p 8000 -c-1",
"test": "karma start karma.conf.cjs",
"test-single-run": "karma start karma.conf.cjs --single-run",
"test": "karma start karma.angularJS.conf.cjs",
"test-single-run": "karma start karma.angularJS.conf.cjs --single-run",
"tsc": "tsc",
"tsc:w": "tsc -w",
"update-webdriver": "webdriver-manager update"
Expand Down
4 changes: 3 additions & 1 deletion tsconfig.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
"outDir": "./out-tsc/spec",
"types": [
"angular",
"jasmine"
"jasmine",
"node",
"angular-mocks"
],
},
"include": [
Expand Down