在 Angular 测试用例中,从服务中进行静态方法调用,其中 HTTP get 将加载存储的 json。并将 json 返回给服务

发布于 2025-01-09 08:05:35 字数 333 浏览 4 评论 0原文

我是新的 Angular 测试用例。并对通过 HTTP 调用加载 JSON 感到震惊。

  • 因此,基本上从服务规范文件:“url-service.spec”调用另一个服务中的静态方法:“load-json.service.spec”。
  • 在“load-json.pservice.spec”中,它进行 HTTP get 调用来加载 json,并自行订阅,然后仅返回 JSON。 [注意:它不会将 observable 返回到 url-service]。

我们可以使用spyOn调用静态方法,但我不知道如何注入HTTP并加载json并在那里订阅

我真的需要帮助!提前非常感谢

I am new Angular test case. And struck with loading JSON via HTTP call.

  • So basically from a service spec file: "url-service.spec" it calls a static method which is in another service: "load-json.service.spec".
  • Here in "load-json.pservice.spec" it makes HTTP get call to load json and also subscribes there itself and then returns only JSON.
    [NOTE: It doesn't return observable back to url-service].

We can call static method using spyOn but I could not figure out how to inject HTTP and load json and subscribe there

I really need help!! And Thanks a lot in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

错爱 2025-01-16 08:05:35

我可以给你举一个我的项目的例子。也许它会帮助你得到一个想法。

describe("Interviews service", () => {
let httpClientSpy: jasmine.SpyObj<HttpClient>;
let interviewsService: InterviewsService;

 beforeEach(() => {
 const apiUrlsServiceFake = jasmine.createSpyObj('ApiUrlsBuilderService', ['getApiUrl']);
 httpClientSpy = jasmine.createSpyObj('HttpClient', ['post']);
interviewsService = new InterviewsService(httpClientSpy, apiUrlsServiceFake);
});

it('should create new interview and return new interview data', (done: DoneFn) => {
const expectedNewInterviewData: NewInterviewData = { id: 1234, encodedId: "qweasd" };

httpClientSpy.post.and.returnValue(asyncData(expectedNewInterviewData));

 interviewsService.createNewInterview(1111, "New interview").subscribe({
  next: newIwData => {
    expect(newIwData).withContext("Expect new interview data").toEqual(expectedNewInterviewData);
    done();
  },
  error: done.fail
});

 expect(httpClientSpy.post.calls.count()).withContext('one call').toBe(1);   });   });

I can give you an example from my project. Maybe it will help you to get an idea.

describe("Interviews service", () => {
let httpClientSpy: jasmine.SpyObj<HttpClient>;
let interviewsService: InterviewsService;

 beforeEach(() => {
 const apiUrlsServiceFake = jasmine.createSpyObj('ApiUrlsBuilderService', ['getApiUrl']);
 httpClientSpy = jasmine.createSpyObj('HttpClient', ['post']);
interviewsService = new InterviewsService(httpClientSpy, apiUrlsServiceFake);
});

it('should create new interview and return new interview data', (done: DoneFn) => {
const expectedNewInterviewData: NewInterviewData = { id: 1234, encodedId: "qweasd" };

httpClientSpy.post.and.returnValue(asyncData(expectedNewInterviewData));

 interviewsService.createNewInterview(1111, "New interview").subscribe({
  next: newIwData => {
    expect(newIwData).withContext("Expect new interview data").toEqual(expectedNewInterviewData);
    done();
  },
  error: done.fail
});

 expect(httpClientSpy.post.calls.count()).withContext('one call').toBe(1);   });   });
蹲在坟头点根烟 2025-01-16 08:05:35

看起来您正在以错误的方式处理问题。您应该模拟“load-json.service.ts”中的方法,模拟的方法应该返回准确的 JSON

如果您正在测试某些组件,以下是我的建议。

请注意,在提供程序中,我们强制组件使用我们模拟的 LoadJsonService。

...
const jsonDataObj = {foo: 'bar'};
const mockedLoadJsonService = {
  getJson:()=> JSON.stringify(jsonDataObj)
}

beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [...],
      providers: [
        { provide: LoadJsonService, useValue: mockedLoadJsonService },
      ],
    }).compileComponents();
  });

...

It looks like you are approaching the problem in the wrong way. You should mock the method in "load-json.service.ts", the mocked method should return the exact JSON

If you are testing some components, the following is what I am suggesting.

Notice in the providers, we are forcing the component to use our mocked LoadJsonService.

...
const jsonDataObj = {foo: 'bar'};
const mockedLoadJsonService = {
  getJson:()=> JSON.stringify(jsonDataObj)
}

beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [...],
      providers: [
        { provide: LoadJsonService, useValue: mockedLoadJsonService },
      ],
    }).compileComponents();
  });

...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文