我正在使用 Typescript 和 Jest 尝试测试我的 Angular 和 Ionic 应用程序的一些组件,但问题不仅限于 Angular 或 Ionic。因此,我正在尝试让 Jest 的模拟功能发挥作用。
我只是创建一个虚拟类,我想尝试模拟函数的响应,看看是否可以覆盖该行为。
玩笑模拟.ts
export class AClass {
constructor() { }
GetOne():any {
return 1;
}
GetTwo():any {
return 2;
}
}
玩笑模拟.spec.ts
import { AClass } from './jest-mock';
// const mockGet = jest.fn( () => { return 3; } ); // Tried this to return 3?
const mockGet = jest.fn();
jest.mock('./jest-mock', () => {
return jest.fn().mockImplementation( () => {
return { GetOne: mockGet };
});
});
describe('Testing Jest Mock is working', () => {
it('should support mocking out the component', () => {
expect(mockGet).toBeTruthy();
expect(mockGet).toBe(3); // Mocked Value
});
});
我只是想创建一个可以更改函数结果的测试,以便其他真实测试代码可以使用我的模拟来提供测试结果。
当我尝试从模拟创建一个类时TestObject = new AClass();
TypeError: _jestMock.AClass is not a constructor
通过上面定义的测试,我收到以下错误:
expect(received).toBe(expected)
Expected value to be (using Object.is):
3
Received:
[Function mockConstructor]
Difference:
Comparing two different types of values. Expected number but received function.