[英]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.