简体   繁体   English

如何在 Jest 测试的 Angular 组件中注入模拟服务

[英]How to inject a mock service in an Angular component tested by Jest

I've used Jasmine+Karma in the past to test my Angular component.我过去曾使用 Jasmine+Karma 来测试我的 Angular 组件。 We are starting a big project and I think it's better we use Jest because it will allow to run in parallel all of our tests (because it will be a project developed over several years and a lot of tests are expected).我们正在启动一个大项目,我认为我们最好使用 Jest,因为它将允许并行运行我们所有的测试(因为这将是一个开发多年的项目,并且预计会有很多测试)。

So now, I've a typical usecase: I've an Angular component that has a dependency on a service (which basically retrieves data from some HTTP calls), and when an action happens (or just at the initialization) I want to ensure the service method has been called and return some mock data.所以现在,我有一个典型的用例:我有一个 Angular 组件,它依赖于一个服务(它基本上从一些 HTTP 调用中检索数据),当一个动作发生时(或者只是在初始化时)我想确保服务方法已被调用并返回一些模拟数据。

With Jasmine, I would do something like:使用 Jasmine,我会做类似的事情:

beforeEach(() => {
  testQuote = 'Test Quote';

  const twainService = jasmine.createSpyObj('TwainService', ['getQuote']);
  getQuoteSpy = twainService.getQuote.and.returnValue(of(testQuote));

  TestBed.configureTestingModule({
    declarations: [TwainComponent],
    providers: [{provide: TwainService, useValue: twainService}]
  });

  fixture = TestBed.createComponent(TwainComponent);
  component = fixture.componentInstance;
  quoteEl = fixture.nativeElement.querySelector('.twain');
});

it('should show quote after component initialized', () => {
  fixture.detectChanges();  // onInit()

  // sync spy result shows testQuote immediately after init
  expect(quoteEl.textContent).toBe(testQuote);
  expect(getQuoteSpy.calls.any())
    .withContext('getQuote called')
    .toBe(true);
});

What would be the equivalent of this with Jest?这与 Jest 的等价物是什么? I did search quite a bit, but I find either examples that are not applicable to Angular, or do not apply to a service injected.我确实搜索了很多,但我发现要么不适用于 Angular 的示例,要么不适用于注入的服务。

(I set up Jest following this, if it helps: https://dev.to/alfredoperez/angular-10-setting-up-jest-2m0l ) (如果有帮助,我会按照此设置 Jest: https://dev.to/alfredoperez/angular-10-setting-up-jest-2m0l

you need to create a mock file which contains all the mock responses that you want to store.您需要创建一个模拟文件,其中包含您要存储的所有模拟响应。 For Example this is the response:例如,这是响应:

export class TestListMockValues { TestData = { status: true, result: { data: [], }, };导出 class TestListMockValues { TestData = { status: true, result: { data: [], }, }; TestResp = { status: true, result: { data: { url: 'dummy_url', }, }, }; TestResp = { status: true, result: { data: { url: 'dummy_url', }, }, };

} }

then under the spec file where you have get the mock value you can easily initialize the object and use it For Example然后在获得模拟值的规范文件下,您可以轻松地初始化 object 并将其用于示例

let testListGetMockValues = new TestListMockValues();

then you can use object and get valus sore them 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何用玩笑模拟组件中使用的“嵌套”角度服务 - How to mock a "nested" angular service used in a component with jest Angular 9 单元测试:如何模拟导入测试组件? - Angular 9 Unit Test: how to mock import of tested component? Angular + Jasmine:如何在测试组件中忽略/模拟一个 function(不依赖)? - Angular + Jasmine: How to ignore/ mock one function in the tested component (not in a dependency)? Angular - 如何使用 Jest 和 NgMocks 模拟包装器组件 - Angular - How to mock wrapper component with Jest and NgMocks 如何使用 JEST (Angular Ts) 模拟服务 - How to mock a service with JEST (Angular Ts) Angular 5-如何将服务注入组件/服务之外 - Angular 5 - How to inject Service outside a component/service Angular Jest or Jasmine Testing: How to Properly Spy/Mock a Static Object Called From Within a Tested Class? - Angular Jest or Jasmine Testing: How to Properly Spy/Mock a Static Object Called From Within a Tested Class? 如何将带有参数化构造函数的服务注入到组件-Angular - How to Inject a Service with Parameterized constructor to a Component - Angular 如何使用Angular2将服务注入动态组件 - How to inject a service into a dynamic component with Angular2 如何在正在测试的组件的OnInit中调用的测试文件中模拟服务? - How to mock a service in a test file that is being called in OnInit of the component being tested?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM