简体   繁体   中英

Mocking service calls in Jest Tests for StencilJs

In my StencilJs application I am writing tests using Jest. I have a component class which uses the Service class to make REST calls. For simplicity here, the service class just has one method which prints some text:

The Component class:

import {sayHello} from './helloworld-service';

@Component({
  tag: 'comp-home',
  styleUrl: 'comp-home.scss',
  shadow: false,
  scoped: true
})
export class MyComponent {

public callHelloWorldService () {
 return sayHello();

} }

The Service class looks like this:

export function   sayHello  () {
 return "Hello!";
}

It has only one function and I want to mock this function in my test method which is as follows:

jest.mock('../helloworld/helloworld-service', () => ({
  sayHello: jest.fn()
}));
import { sayHello } from '../helloworld/helloworld-service';

const mockSayHello = sayHello as jest.Mock;


describe('mycomp-tests', () => {

  let compInstance;

  beforeEach(() => {
    mockSayHello.mockClear();
    compInstance = new MyComponent();
  });
  afterEach(() => {
    jest.clearAllMocks();
  });


  it('should return mock value', () => {
   mockSayHello.mockReturnValue("yahoo");
   expect(compInstance.callHelloWorldService()).toBe("yahoo");
  });

I have used the this tutorial for https://mikeborozdin.com/post/changing-jest-mocks-between-tests/ writing the mocks.

Now, the issue I am facing is that if I call mocked service method directly in the test, the mocked instance is called and the test passes:

 it('should return mock value', () => {
   mockSayHello.mockReturnValue("yahoo");
   expect(compInstance.callHelloWorldService()).toBe("yahoo");
  });

But if I call the service method via my component, then the original method in the service is called instead of the mocked method and test fails:

  it('should return mock value', () => {
   mockSayHello.mockReturnValue("yahoo");
   expect(compInstance.callHelloWorldService()).toBe("yahoo");//Fails ,return value is Hello !
  });

How can I ensure that the components also call the mocked methods? This behaviour is needed to mock REST calls in the test etc.

I mocked functions like this in stencil unit tests

import * as HelloworldService from '../helloworld/helloworld-service';

HelloworldService.sayHello = jest.fn().mockReturnValue("yahoo");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM