Я просмотрел несколько примеров, но не смог сопоставить свой случай с тем, как шпионить за свойствами динамического c.
Простые заказы и детали заказа в приложении ioni c 4. Список заказов на странице «Заказы» и после нажатия на один из заказов он передает весь объект заказа на страницу сведений о заказе.
Ниже приведена страница сведений о заказе.
@Component({
selector: 'app-order-details',
templateUrl: './order-details.page.html',
styleUrls: ['./order-details.page.scss'],
})
export class OrderDetailsPage implements OnInit {
orderData: Order;
users: Map<any, any>;
location$: Subscription;
data = {order : null};
constructor(
private dataService: DataService,
) {
//const data = this.dataService.getData();
this.data = this.dataService.getData();
this.orderData = this.data.order;
}
Короче говоря, извлечение порядка данных из dataService.getData () и использование на странице сведений о заказе.
Ниже приведено описание детали заказа c .ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { OrderDetailsPage } from './order-details.page';
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
import { RouterModule } from '@angular/router';
import { DataService } from 'src/app/services/data.service';
describe('OrderDetailsPage', () => {
let component: OrderDetailsPage;
let fixture: ComponentFixture<OrderDetailsPage>;
let datasvcSpy;
beforeEach(async(() => {
var datasvc = new DataService();
spyOn(datasvc,"getData").and.returnValue({order : {id : "12",description:"desc"}});
//spyOn(component.data,'order'). and.returnValue({id : "12",description:"desc"});
//datasvcSpy = jasmine.createSpyObj('DataService',["getData"]);
TestBed.configureTestingModule({
declarations: [OrderDetailsPage],
imports: [IonicModule.forRoot(),
HttpClientTestingModule,
RouterModule.forRoot([]),
]
}).compileComponents();
fixture = TestBed.createComponent(OrderDetailsPage);
component = fixture.componentInstance;
//component.data = { order: { id: "123", description: "desc" } };
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
Все комментарии в приведенном выше файле являются различными следами, но не работали.
Ниже приведен npm отчет о выполнении теста:
Chrome 80.0.3987 (Mac OS X 10.14.6): Executed 2 of 10 (1 FAILED) (0 secs / 0.542 secs)
Chrome 80.0.3987 (Mac OS X 10.14.6) OrderDetailsPage should create FAILED
Failed: Cannot read property 'order' of undefined
error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33669121, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 114688, directChildFlags: 114688, childMatchedQueries: 0, matchedQueries: Object({ }), matchedQueryIds: 0, references: Object({ }), ngContentIndex: null, childCount: 1, bindings: [ ], bindingFlags: 0, outputs: [ ], element: Object({ ns: '', name: 'app-order-details', attrs: [ ], template: null, componentProvider: Object({ nodeIndex: 1, parent: <circular reference: Object>, renderParent: <circular reference: Object>, bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 114688, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ngContentIndex: -1, childCount: 0, bindings: Array, bindingFlags: 0, outputs ...
at <Jasmine>
at new OrderDetailsPage (http://localhost:9876/_karma_webpack_/src/app/orderDetails/components/order-details/order-details.page.ts:28:32)
at createClass (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:31991:1)
at createDirectiveInstance (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:31807:1)
at createViewNodes (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:44210:1)
at createRootView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:44082:1)
at callWithDebugContext (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:45632:1)
at Object.debugCreateRootView [as createRootView] (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:44848:1)
at ComponentFactory_.create (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:30788:1)
at initComponent (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/testing.js:3946:1)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)
Error: Expected undefined to be truthy.
at <Jasmine>
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/orderDetails/components/order-details/order-details.page.spec.ts:41:23)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)
at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/z
edit # 2
Изменен файл spe c после рекомендации:
describe('OrderDetailsPage', () => {
let component: OrderDetailsPage;
let fixture: ComponentFixture<OrderDetailsPage>;
let datasvcSpy;
let mockDataService = { getData: () => { } };
beforeEach(async(() => {
var datasvc = new DataService();
mockDataService = spyOn(datasvc, "getData").and.returnValue({ order: { id: "12", description: "desc" } });
TestBed.configureTestingModule({
declarations: [OrderDetailsPage],
imports: [IonicModule.forRoot(),
HttpClientTestingModule,
RouterModule.forRoot([]),
],
providers: [{ provide: DataService, useValue: mockDataService }]
}).compileComponents();
fixture = TestBed.createComponent(OrderDetailsPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
, но это приводит к ошибке компиляции:
ERROR in src/app/orderDetails/components/order-details/order-details.page.spec.ts:23:5 - error TS2741: Property 'getData' is missing in type 'Spy<() => any>' but required in type '{ getData: () => void; }'.
23 mockDataService = spyOn(datasvc, "getData").and.returnValue({ order: { id: "12", description: "desc" } });
~~~~~~~~~~~~~~~
src/app/orderDetails/components/order-details/order-details.page.spec.ts:15:27
15 let mockDataService = {getData: () => {} };
~~~~~~~~~~~~~~~~~