使用Mocks使用Jest和Typescript进行测试

时间:2018-02-05 22:52:16

标签: unit-testing typescript jest

我正在使用Typescript和Jest尝试为我的Angular和Ionic应用程序测试一些组件,但问题不仅限于Angular或Ionic。因此,我试图让Jest的模拟功能起作用。

我只是创建一个虚拟类,我想尝试模拟函数的响应,看看我是否可以覆盖行为。

开玩笑-mock.ts

export class AClass {
    constructor() { }

    GetOne():any {
        return  1;
    }

    GetTwo():any {
        return 2;
    }
}

开玩笑-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
    });
});

我只是想创建一个可以改变函数结果的测试,这样我的mock就会被其他真正的测试代码用来提供测试结果。

当我尝试从模拟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.

1 个答案:

答案 0 :(得分:5)

在检查其他引用时,我确实设法让模拟测试工作。我将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();
    });
});