【问题标题】:Mocking service calls in Jest Tests for StencilJs在 StencilJs 的 Jest 测试中模拟服务调用
【发布时间】:2022-02-27 17:57:24
【问题描述】:

在我的 StencilJs 应用程序中,我正在使用 Jest 编写测试。我有一个组件类,它使用服务类进行 REST 调用。为简单起见,服务类只有一个打印一些文本的方法:

组件类:

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

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

public callHelloWorldService () {
 return sayHello();

} }

Service 类如下所示:

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

它只有一个函数,我想在我的测试方法中模拟这个函数,如下所示:

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");
  });

我已经使用本教程来编写 https://mikeborozdin.com/post/changing-jest-mocks-between-tests/ 模拟。

现在,我面临的问题是,如果我直接在测试中调用模拟服务方法,则调用模拟实例并且测试通过:

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

但是如果我通过我的组件调用服务方法,则调用服务中的原始方法而不是模拟方法并且测试失败:

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

如何确保组件也调用模拟方法?在测试等中模拟 REST 调用需要此行为。

【问题讨论】:

    标签: javascript typescript jestjs stenciljs


    【解决方案1】:

    我在模板单元测试中模拟了这样的函数

    import * as HelloworldService from '../helloworld/helloworld-service';
    
    HelloworldService.sayHello = jest.fn().mockReturnValue("yahoo");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 2021-11-05
      • 2023-01-30
      • 2021-09-11
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多