使用 Jest,如何模拟在被测试类的另一个静态方法中使用的静态方法?

问题描述 投票:0回答:1

我有两个类

ClassA
ClassB
只包含静态方法。
ClassA
中的一个方法,称为
staticMethodA()
,调用来自
ClassB
的静态方法,称为
staticMethodB

import { ClassB } from './classB'

export class ClassA {
    public static async staticMethodA() {
        return await ClassB.staticMethodB();
    }
}

在为

staticMethodA()
进行单元测试时,我想模拟
staticMethodB()
以更好地隔离
staticMethodA()
。按照现有的在线指导,我创建了以下测试:

    describe('staticMethodA', () => {
        let classA;

        const mockStaticMethodB = jest.fn().mockResolvedValue({}); //return dummy object

        beforeAll(() => {

            // Mocking ClassB
            jest.mock('../src/classB', () => () => ({

                ClassB: { 
                    staticMethodB: mockStaticMethodB
                }

            })}};

            // Importing ClassA after mocking ClassB so it references the mock
            classA = require('../src/classA');
        }

        it('should call mockStaticMethodB', async () => {

            //The object returned from require is an object containing ClassA
            const actual = await classA.ClassA.staticMethodA();

            expect(actual).toBe({}); // dummyObject
        }

        afterAll(() => {
            jest.unmock('../src/classB');
        });
    }

当 staticMethodA 调用 staticMethodB 时,我得到一个错误,指出 ClassB 未定义。当我在

return await ClassB.staticMethodB();
上设置断点时,我看到有一个名为
classB_1
的变量可用但不是
ClassB
.

我已经尝试了以下资源中的一些模拟构建策略,但仍然导致

ClassB
未定义:

typescript jestjs mocking dependencies static-methods
1个回答
1
投票

在这种情况下,有几件事需要改变。我已经在本地测试过它并且有效。

// classa.test.ts
import {ClassA} from '../classA';
// we are importing ClassB directly
// this will be the mocked version
import {ClassB} from '../classB';

// mock should be hoisted to the top of the module
jest.mock('../classB', () => {
    return {
        ClassB: {
            staticMethodB: jest.fn(),
        },
    };
});

describe('classA', () => {
    it('should call mockStaticMethodB', async () => {
        // since ClassB is a mock we can provide the return value for this test case only
        (ClassB.staticMethodB as jest.Mock).mockReturnValueOnce(42);
        const actual = await ClassA.staticMethodA();

        // note that in both mock and here we are using 42 for comparison as it works with `expect().toBe()`
        // if we wanted to compare objects we would use `expect().toEqual()` instead
        expect(actual).toBe(42);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.