{"id":3898,"date":"2020-08-05T14:53:45","date_gmt":"2020-08-05T14:53:45","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=3898"},"modified":"2020-08-05T15:25:34","modified_gmt":"2020-08-05T15:25:34","slug":"mocking-dependent-objects-in-jasmine","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/mocking-dependent-objects-in-jasmine\/","title":{"rendered":"Mocking Dependent Objects in Jasmine"},"content":{"rendered":"<p><strong class=\"ctaHeader2\">Mocking Dependency Injection Objects<\/strong><br \/>\nThere may be times where the service would be injected into the component using constructor by DI. In such a case while creating a component instance for test class we could end up with a problem. To answer this we pass mock objects as alternate to constructors<\/p>\n<p><strong>add.employee.component.ts<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nexport class EmployeeComponent implements OnInit {\r\n .\r\n .\r\n  constructor(private objEmpserviceService : EmpserviceService) {\r\n  }\r\n\r\n  checkForAuthentication(): string {\r\n    if(this.objEmpserviceService.authenticateEmp('Admin')){\r\n      return &quot;You are allowed to Edit&quot;;\r\n    }\r\n    return &quot;You are Not allowed to Edit&quot;;\r\n  }\r\n .\r\n .\r\n<\/pre>\n<p><strong class=\"ctaHeader2\">Two Methods to Answer this Problem<\/strong><br \/>\n<strong>Method 1<\/strong> : If you are not going to call the mockedObject methods <\/p>\n<p>To address this the injected object using dependency injection we use providers. Providers provide mockedobject to constructor instead of real object like below <\/p>\n<p><strong>add.employee.component.spec.ts<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nlet mockEmpserviceService:EmpserviceService;\r\n\r\nbeforeEach(async(() =&gt; {\r\n    mockEmpserviceService = jasmine.createSpyObj(&#x5B;'authenticateEmp', 'addEmployee', 'deleteEmployee']); \r\n\r\n    TestBed.configureTestingModule({\r\n      .\r\n      declarations: &#x5B; EmployeeComponent ],\r\n      providers : &#x5B; \r\n                   {provide:EmpserviceService, useValue:mockEmpserviceService}\r\n                  ]\r\n      .\r\n      .\r\n    }).compileComponents();\r\n  }));\r\n<\/pre>\n<\/li>\n<li>Now in the above code we have mocked the service using mockEmpserviceService and providing a list of methods. But the returnType is still missing. So this could be used only to check if the actual method under test is called without using callThrough which in turn calls the method in mockedObject.\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n .\r\n it('Check for Service Method', ()=&gt;{\r\n    spyOn(component, 'checkForAuthentication');\r\n   \r\n    let auth = component.checkForAuthentication();\r\n    (or)\r\n    const btnAddEmp = fixture.debugElement.query(By.css(&quot;#btnAddEmp&quot;));\r\n    btnAddEmp.triggerEventHandler('click', {});\r\n    fixture.detectChanges();\r\n     \r\n    expect(auth).toHaveCalled();\r\n });\r\n .\r\n<\/pre>\n<p><strong>Method 2<\/strong> : If you are going to call the mocked object methods then in such case the return type of the method should be defined.The same code can be done using actual EmpserviceService in provider and using spyOn inside its block to define the returnType of service method. <\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nlet empService: EmpserviceService;\r\n\r\nbeforeEach(async(() =&gt; {\r\n    TestBed.configureTestingModule({\r\n      declarations: &#x5B; EmployeeComponent],\r\n      providers : &#x5B; EmpserviceService],\r\n      imports: &#x5B;HttpClientTestingModule]\r\n    })\r\n    .compileComponents();\r\n\r\n    empService = Testbed.inject(EmpserviceService);\r\n  }));\r\n\r\n  fit('Check for Service Method', ()=&gt;{  \r\n    \/\/Mocking authenticateEmp to return true as if it is called    \r\n    spyOn(empService, 'authenticateEmp').withArgs('Admin').and.returnValue(true);      \r\n    spyOn(component, 'checkForAuthentication').and.callThrough();\r\n    let auth = component.checkForAuthentication();\r\n    expect(auth).toBe('You are allowed to Edit');\r\n  })\r\n<\/pre>\n<p>In the above code, checkForAuthentication calls authenticateEmp in empService since it does callThrough. <\/p>\n<p><strong>Note:<\/strong>Even now the control doesnt goes through empService. It would be called and returnvalue would be sent back.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Mocking Dependency Injection Objects There may be times where the service would be injected into the component using constructor by DI. In such a case while creating a component instance for test class we could end up with a problem. To answer this we pass mock objects as alternate to constructors add.employee.component.ts export class EmployeeComponent&hellip; <a href=\"https:\/\/codethataint.com\/blog\/mocking-dependent-objects-in-jasmine\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[321],"tags":[],"class_list":["post-3898","post","type-post","status-publish","format-standard","hentry","category-mocking"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3898","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=3898"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3898\/revisions"}],"predecessor-version":[{"id":3908,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3898\/revisions\/3908"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=3898"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=3898"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=3898"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}