【问题标题】:Mock a class for testing with Typescript and Jest模拟一个使用 Typescript 和 Jest 进行测试的类
【发布时间】:2018-03-31 01:10:07
【问题描述】:

我正在尝试使用带有 Angular 和 Typescript 的 Jest 编写测试,但我不太明白如何模拟类中的函数。我创建了一个非常简单的示例,试图在理解我不遵循的内容方面获得一些帮助。

test-service.ts(简单类)

export class TestService{
    constructor() { }

    GetRandom(): number {
        return Math.floor(Math.random() * 100);
    }
}

这是一个简单的类,只是为了展示我想要模拟的东西。由于该函数返回一个随机数,因此您无法对其进行测试。这是我试图简单说明可能返回任何内容的外部进程的示例,并希望检查返回的数据是否我的代码可以正常工作。

test-service.spec.ts

import { TestBed, ComponentFixture } from '@angular/core/testing';

import { NO_ERRORS_SCHEMA } from '@angular/core';

jest.mock('./test-service');
import { TestService } from './test-service';

describe('TestService', () => {
    let TestObject: TestService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ ],
            providers: [ ]
        });
    });

    describe('Sample Test', () => {
        test('Random Number should be mocked by Jest', () => {
            ...  // What do to here??
            expect(TestObject.GetRandom()).toBe(5);  // How do I get the mock here?

        });
    });
});

我不知道如何让随机数返回一个简单的数字(例如 5)进行测试。

【问题讨论】:

    标签: angular typescript jestjs


    【解决方案1】:

    首先,您必须创建一个方法来替换所需模拟方法的实现。比如我在TestUtil类中创建的:

    export class TestUtil {
    
     public static mockService(service: any, methods: string[]) {
       @Injectable()
       class MockedClass {
       }
    
       methods.forEach(method => MockedClass.prototype[method] = Observable.of({}));
    
       return {provide: service, useClass: MockedClass};
      }
    }
    

    然后您可以使用它在您的测试模块中提供 TestService 的模拟类。

    describe('TestService', () => {
      let TestObject: TestService;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [TestUtil.mockService(TestService, ['GetRandom'])]
        });
      });
    
      beforeEach(inject([TestService], (injectedTestService: TestService) => {
        TestObject = injectedTestService;
      }));
    
      describe('Sample Test', () => {
        test('Random Number is mocked by You', () => {
           spyOn(TestObject, "GetRandom").and.returnValue(5);
           expect(TestObject.GetRandom()).toBe(5);
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2023-04-01
      • 2017-02-25
      • 1970-01-01
      • 2021-08-15
      • 2021-01-13
      • 2017-02-13
      • 2020-01-23
      • 2018-12-18
      相关资源
      最近更新 更多