Angular + Jasmine: How to ignore/ mock one function in the tested component (not in a dependency)?


I know how to mock a function from a dependency, but now I have one function that is not in a dependency, it’s in the actual component that I want to test. How can I tell jasmine to simply ignore it?

When I run ng test this test fails:

enter image description here

The reason for this is this function that I import from an external library:

import { documentToHtmlString } from '@contentful/rich-text-html-renderer';

(Contentful is a content managament service that I use in my project.)

In my component this function gets called here:

ngOnInit() {
  //the next line keeps the test from creating, I don't really care to test this function, how can I mock it?:
  // a lot more stuff that I actually need to test

serializeContentfulRichText(contentfulText: any) {
    return documentToHtmlString(contentfulText, this.myRenderingOptions);

When I delete the documentToHtmlString line and just return null the rest of the test works and I can test my whole component. But of course I can’t just delete this line in my actual component, I just want to ignore/mock it in my test.

I tried it with a spy:

it('should create', () => {
    let spy = spyOn(component, 'serializeContentfulRichText')

But the spy doesn’t get called and the component doesnt get created (Both expectations fail).

Source: Angular Questions

Categorized as angular, contentful, jasmine, mocking, unit-testing Tagged , , , ,


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?

Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us