【问题标题】:Testing with Jest and Typescript using Mocks使用 Mocks 使用 Jest 和 Typescript 进行测试
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 1970-01-01
      • 2021-08-15
      • 2020-01-23
      • 2018-03-31
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多