【发布时间】:2023-04-01 10:08:01
【问题描述】:
我正在使用 Typescript 和 Jest 尝试为我的 Angular 和 Ionic 应用程序测试一些组件,但问题不仅限于 Angular 或 Ionic。因此,我试图让 Jest 的模拟功能发挥作用。
我只是创建一个虚拟类,我想尝试模拟函数的响应,看看我是否可以覆盖行为。
jest-mock.ts
export class AClass {
constructor() { }
GetOne():any {
return 1;
}
GetTwo():any {
return 2;
}
}
jest-mock.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.
【问题讨论】:
标签: unit-testing typescript jestjs