这是我的项目:
模拟测试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
?
任何帮助,将不胜感激。
看看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')
})
})