Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - Jasmine Test Error : Expected Spy XYZ to have been called

I have a method in component.ts file, which is calling a service method. The code structure is like as following-

getDetails(){
  if(!alreadyCached){
     callLogFunction();
  }
  this.service.getData()
  .then(res => {
    //rest of the logic here
  })
  .catch(err=>{ //catch logic here })
}

My test block looks like this-

it('should call service.getData', ()=>{
  spyOn(service,'getData').and.returnValue(Promise.resolve([]);
  component.getDetails();
  fixture.whenStable().then(()=>{
    expect(service.getData).toHaveBeenCalled();
  }
}

Why am I getting error that expected spy getData to have been called It would be great if you can help me with testing then and catch block (how to write tests for them)

Thanks! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are trying to test that service.getData is called, as per your test name, you should write the test thus:

it('should call service.getData', ()=>{

  const getDataSpy = spyOn(service,'getData');

  component.getDetails();

  expect(getDataSpy).toHaveBeenCalled();
  
}

That way you have tested only that which you want to test, that the service method is called, without having other distractions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...