【发布时间】:2019-08-02 09:42:41
【问题描述】:
我想模拟反应类的方法,以便单元测试可以跟随模拟功能运行。
反应:16.8.6 开玩笑:24.8.0
Overview.js
import React from 'react';
export default class Overview extends Component{
test1(){
return {
// fetch api
}
}
test2(){
const result = this.test1();
// do other thing
return result
}
}
overview.test.js
import Overview from './index';
import { mount } from 'enzyme';
import React from 'react';
describe('test Overview',()=>{
const mockResult = {test1:'test1'};
console.info(Overview.prototype) // {}
Overview.prototype.test1=jest.fn(()=>{
return mockResult
});
it('func test2',()=>{
const wrapper = mount(<Overview/>);
const {test2} = wrapper.instance();
expect(mockResult).toEqual(test2())
})
})
期望:运行成功
实际结果:运行失败,因为 Overview.prototype 无法覆盖或模拟 test1 函数。
当我尝试打印“Overview.prototype”时,我得到了 {}。这让我很困惑。
如何模拟 test1 函数以及为什么不能覆盖概览?
请帮帮我。
【问题讨论】:
-
我试图从官方api中找到一些东西。 api 使用 jest.fn(), jest.spyon() 来模拟函数,但这些演示只模拟整个函数或模块,而不是类的单个方法。
标签: reactjs unit-testing jestjs