如何模拟特定功能而不影响同一个ES6类中的其他功能?

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

这是我的项目:

模拟测试Dependency.js:

export default class MockTestDependency {
    testAction1() {
        return 'testAction1'
    }

    testAction2() {
        return 'testAction2'
    }
}

模拟Test.test.js:

jest.mock('./MockTestDependency')

import MockTestDependency from './MockTestDependency'

beforeAll(() => {
    MockTestDependency.mockImplementation(() => {
            return {
                testAction1: () => {return 'mocked1'},
            }
        }
    )
})

describe('mock test 3', () => {
    it('first case', () => {
        let mockTestDependency = new MockTestDependency()
        expect(mockTestDependency.testAction1()).toBe('mocked1')
        expect(mockTestDependency.testAction2()).toBe('testAction2')
    })
})

运行jest命令后发生错误:

TypeError: mockTestDependency.testAction2 is not a function

那么,如何模拟功能testAction1而不影响功能testAction2

任何帮助,将不胜感激。

mocking jestjs
1个回答
1
投票

看看jest.spyOn()函数,它允许模拟只选择的方法。当你使用jest.mock('./MockTestDependency')时,它会将模块中的所有方法嘲弄到jest.fn()

import MockTestDependency from './MockTestDependency'

beforeAll(() => {
    jest.spyOn(MockTestDependency, 'testAction1').mockImplementation(() => 'mocked1');
})

describe('mock test 3', () => {
    it('first case', () => {
        let mockTestDependency = new MockTestDependency()
        expect(mockTestDependency.testAction1()).toBe('mocked1')
        expect(mockTestDependency.testAction2()).toBe('testAction2')
    })
})
© www.soinside.com 2019 - 2024. All rights reserved.