angular - 模拟类以使用 Typescript 和 Jest 进行测试

标签 angular typescript jestjs

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

test-service.ts(简单类)

export class TestService{
    constructor() { }

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

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

测试服务.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)来进行测试。

最佳答案

首先,您必须创建一个方法来替换所需模拟方法的实现。例如,我在类 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);
    });
  });
});

关于angular - 模拟类以使用 Typescript 和 Jest 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46822392/

相关文章:

javascript - 如何将链的 promise 转换为 Q 和 TypeScript 中的平面 promise

typescript - TS-Jest 无法解析 tsconfig 路径

reactjs - 当react test-utils引用ReactComponent树时,它期望什么?

Angular 路由自动重定向到默认路径

sqlite - ionic 2 错误 'ReferenceError: sqlitePlugin is not defined'

angular - Electron/Angular 示例应用程序中的“TypeError: window.require is not a function”

node.js - 当我需要验证数组的内容时,NestJS 中的 ValidationPipe 出现问题

TypeScript 声明特定的 SCSS 模块

angular - 无法绑定(bind)到 'matMenuTriggerFor',因为它不是 'button' 的已知属性

angularjs - tsconfig 模块选项 - 'System' 是指 SystemJS 吗?