0
export class AddRouteComponent implements OnInit {
workforce: Workforce;

save() {
  workforce = new Workforce();
  workforce.name = form.controls.value("name");
}
}

This is obviously a simplified version of what I'm trying to test. I'd like to write a jasmine test that has workforce equal a const of the object so I can properly test all properties of that object. Normally I'd have component.workforce = testWorkforce, but the new Workforce doesn't allow this to work.

Is there a way to do this?

lank81
  • 45
  • 6
  • Mock the Workforce. – Jai Sep 02 '22 at 03:44
  • @Iank81 the code you share does not return anything or sets any global variable so you can't test anything, if you want to fulfill coverage just check if `value` method is called inside the function! – Naren Murali Sep 02 '22 at 07:03

1 Answers1

0

Unfortunately, we can't mock new Workforce(). The best way I have found to do it is using the following response: https://stackoverflow.com/a/62935131/7365461.

For you, it could be:

1.) Create a wrapper class.

export class WorkforceWrapper() {
  static createWorkforce() {
     return new Workforce();
  }
}

2.) Use wrapper class in component or class.

save() {
  workforce = WorkforceWrapper.createWorkforce();
  // the rest
}

3.) Modify your tests:

spyOn(WorkforceWrapper, 'createWorkforce').and.returnValue({/* return whatever you wish here */ });
AliF50
  • 16,947
  • 1
  • 21
  • 37