Ste*_*ott 8 unit-testing typescript jest
我正在与Typescript和Jest一起尝试为我的Angular和Ionic应用程序测试某些组件,但是问题不仅仅限于Angular或Ionic。因此,我正在尝试使Jest的模拟功能起作用。
我只是在创建一个虚拟类,我想尝试模拟函数的响应以查看是否可以覆盖行为。
开玩笑
export class AClass {
constructor() { }
GetOne():any {
return 1;
}
GetTwo():any {
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
玩笑样张
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
});
});
Run Code Online (Sandbox Code Playgroud)
我只是试图创建一个可以更改函数结果的测试,以便其他模拟测试代码可以使用我的模拟来提供测试结果。
当我尝试通过模拟创建类时 TestObject = new AClass();
TypeError: _jestMock.AClass is not a constructor
Run Code Online (Sandbox Code Playgroud)
通过上面定义的测试,我得到以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
在检查其他参考时,我确实设法使模拟测试正常工作。我将jest-mocks.spec.ts更改为:
jest.mock('./jest-mock', () => {
return { // Define Function Mock Return Values
GetOne: jest.fn( () => 3 )
}
});
const MockObject = require('./jest-mock');
describe('mock function', () => {
it('should create mock', () => {
expect(jest.isMockFunction(MockObject.GetOne)).toBeTruthy();
});
it('should return mock values', () => {
expect(MockObject.GetOne()).toBe(3);
expect(MockObject.GetOne).toHaveBeenCalled();
expect(MockObject.GetTwo).toBeUndefined();
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9241 次 |
最近记录: |