【发布时间】: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