gpt4 book ai didi

angular - 使用 Jest 和 Testbed 测试 Angular 9 服务

转载 作者:行者123 更新时间:2023-12-05 02:55:29 25 4
gpt4 key购买 nike

在我的 Angular 9 项目中,我添加了 jest 并删除了 JasmineKarma

我正在测试名为 CorrectionService 的服务,它依赖于名为 RemoteService 的服务。

我想监视 RemoteService 以查看是否调用了某个方法。我已经通过 Jest 手动模拟 RemoteService 成功地完成了它。

现在我想使用 TestBed。我之前的 Jasmine 测试是这样的:

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
import { CorrectionService } from './correction.service';
import { Answer, Question } from './setting';
import { IChoosed } from './question/question.component';
import { RemoteService } from './remote.service';


describe('CorrectionService', () => {
let service: CorrectionService;
let remoteServiceSpy: jasmine.SpyObj<RemoteService>

beforeEach(() => {
const spy = jasmine.createSpyObj('RemoteService', ['saveToRemoteAdditionalData']);
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
CorrectionService,
{provide: RemoteService, useValue: spy}
]
});
service = TestBed.inject(CorrectionService);
remoteServiceSpy = TestBed.inject(RemoteService) as jasmine.SpyObj<RemoteService>;
});

我试过以这种方式使用 jest 模拟:

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { CorrectionService } from './correction.service';
import { Answer, Question } from './setting';
import { IChoosed } from './question/question.component';
import { RemoteService } from './remote.service';


describe('CorrectionService', () => {
let service: CorrectionService;
this.remoteServiceStub = {} as RemoteService;

beforeEach(() => {
this.remoteServiceStub = {saveToRemoteAdditionalData: jest.fn()};

TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers:[
CorrectionService,
{provide:RemoteService, useValue: this.remoteServiceStub}
]
});
this.service = TestBed.inject(CorrectionService);
TestBed.inject(RemoteService);
});

但是测试没有工作,我得到了:

 Can't resolve all parameters for CorrectionService: (?).

我猜 RemoteService 没有被注入(inject)。我做错了什么?

最佳答案

我发现了问题,我在 tsconfig.spec.json 中放错了 emitDecoratorMetadata 属性。它不在 compilerOptions 中。

我把文件的全部内容写在这里以备日后引用:

{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jest",
"node"
],
"emitDecoratorMetadata": true,
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"esModuleInterop": true,
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

关于angular - 使用 Jest 和 Testbed 测试 Angular 9 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61225713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com