我正在尝试使用 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/