【问题标题】:Unit Test: How to mock specific function with jest?单元测试:如何用玩笑模拟特定功能?
【发布时间】:2020-09-14 15:12:07
【问题描述】:

我想在 render 中测试一些东西,但是 getLocationParse() 需要接收 location.search

export default class EstateDetail extends Component {
    constructor(){
        super();

        const parsed = this.getLocationParse();
        ...     
    }

    getLocationParse(){
        const queryString = require('query-string');
        const parsed = queryString.parse(location.search);
        return parsed;
    }

      render() {...}
}

所以我尝试模拟 getLocationParse 但失败了。

知道怎么解决吗?

const getLocationParse = jest.fn().mockReturnValueOnce({id:21});

let app = shallow(
    <EstateDetail/>
);

【问题讨论】:

    标签: reactjs mocking jestjs


    【解决方案1】:

    你可以这样做:

    import { foo } from './example';
    
    jest.mock('./example', () => ({
      ...require.requireActual('./example'),
      foo: jest.fn()
    }));
    
    test('foo should be a mock function', () => {
      expect(foo('mocked!')).toHaveBeenCalledWith('mocked!');
    });
    

    更多信息可以阅读GH问题:https://github.com/facebook/jest/issues/936

    【讨论】:

    • expect(foo('mocked!')).toHaveBeenCalledWith('mocked!'); - 你能解释一下函数'foo'是如何返回这个结果的吗?
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2018-09-25
    • 2020-04-28
    • 2021-06-16
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多