这是我的项目:
MockTestDependency.js:
export default class MockTestDependency {
testAction1() {
return 'testAction1'
}
testAction2() {
return 'testAction2'
}
}
MockTest.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
?
任何帮助都将不胜感激。
答案 0 :(得分: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')
})
})