angular 8 jest 测试 `toHaveBeenCalledWith` 失败,如何测试 api url 调用?

angular 8 jest test `toHaveBeenCalledWith` fails, how to test api url calls?

在我的测试规范中,我想投保 2 个东西。

1. dummy data maching with model and get response.
2. find the `api` called with correct url.

我正在尝试这些,但出现错误:

SubsystemServiceService › get susbsytem collection › should call get the subsytem collection

我也想更新我的规范文件以确保满足我的要求。有人可以帮我吗?

这是我的 spec.ts 文件:

import { TestBed } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { cold } from 'jasmine-marbles';
import { ModelSubSystem } from './../models/model.subSystem';
import { SubsystemService } from './subsystem-service';

describe('SubsystemServiceService', () => {

    let service: SubsystemService;
    let http: HttpClient;

    const data1 = {
        Id: 0,
        Name: 'subsystem1',
        IsDeletePossible: true,
        CreatedBy: '',
        CreatedDate: new Date(),
        UpdatedBy: '',
        UpdatedDate: new Date(),
        UpdatedByName: '',
        CreatedByName: ''
    } as ModelSubSystem;

    const data2 = {
        Id: 0,
        Name: 'subsystem2',
        IsDeletePossible: true,
        CreatedBy: '',
        CreatedDate: new Date(),
        UpdatedBy: '',
        UpdatedDate: new Date(),
        UpdatedByName: '',
        CreatedByName: ''
    } as ModelSubSystem;

    const subsystems = [data1, data2];

    beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [{ provide: HttpClient, useValue: { get: jest.fn() } }]
        });

        service = TestBed.get(SubsystemService);
        http = TestBed.get(HttpClient);

    });

    describe('get susbsytem collection', () => {

        it('should call get the subsytem collection', () => {

            const response = cold('(-a|)', { a: subsystems });
            http.get = jest.fn(() => response);

            expect(http.get).toHaveBeenCalledWith(`https://ewsanedevaoscmsapi01-as.websites.net/api/SubSystem`);

        });
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });

});

你的实际行动在哪里?在测试中应该有三件事

准备

描述('get susbsytem collection', () => {

    it('should call get the subsytem collection', () => {

        const response = cold('(-a|)', { a: subsystems });
        http.get = jest.fn(() => response);

执行

因此您需要执行一些操作,然后检查结果。像

service.get();

断言

        expect(http.get).toHaveBeenCalledWith(`https://ewsanedevaoscmsapi01-as.websites.net/api/SubSystem`);

    });
});

说明

假设您想测试服务的以下方法:

getSubsystems() {
    // Some code lead
    // ...
    // One path leads to get
    if (some condition)
        return http.get('url');
}

为了测试场景

it('should call the url when some condition is fulfilled')

您需要: 1. 设置条件使 'some condition' 成立 2. 创建模拟响应和间谍 const response = cold('(-a|)', { a: subsystems }); 3.创建服务实例,调用代码测试getSubsystems() 4. 断言调用代码后,http.get 已使用预期参数调用。

如果不执行 3,测试框架不知道要执行哪个单元(方法),因此什么都不执行。