簡體   English   中英

Angular - 如何在單元測試中模擬外部 function?

[英]Angular - How can I mock an external function in a unit test?

I'm trying to write an angular unit test for a function that has a dependency on an imported function - how can write a unit test that mocks the results of the imported function? 我擁有的 function 是:

import { DependentMethod } from './dependentMethod';

export function doSomething() {
  const dependentResults = DependentMethod(); // DependentMethod makes an http call and returns the result
  return dependentResults;
}

在這種情況下,我想測試doSomething並模擬DependentMethod function。 當我之前嘗試模擬東西時,我在 class 方法上使用了spy ,但我不確定在這種情況下如何處理它。 任何幫助將不勝感激!

您可以嘗試以下方法,

import { dependent } from './dependentLibrary'; 


describe('yourCoponent', () => {
  let component: yourComponent;
  let service : dependentService;

  beforeEach(() => {
    service = new dependent(null); // if your service has further dependency
    component = new yourComponent(service);
  });

  it('should perform test', () => {
    // Arrange part --> 
    spyOn(service, 'dependentMethod').and.callFake(() => {
      return Observable.from([ [1,2,3] ]); // return your mock data
    });

    //Act part
    component.ngOnInit();

    //Assert
    expect(component.testable.action).toBe(value);

  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM