玩笑-mockReturnValue

hlo*_*rey 6 jestjs

我有一个正在尝试为其添加单元测试的函数。

功能

        async getStuff() {
           const { foo } = this.props.data;
           const { bar } = this.state;
           const { bazz } = this.props;

           const { x, y } = await helpers.getStuffFromServer(foo, bar, bazz);

           this.setState({ x, y });
        }
Run Code Online (Sandbox Code Playgroud)

测试

        it('should get stuff & set state', async() => {
           const returnObject = {
               x: dummyData.x,
               y: dummyData.y
           };
           getStuff.mockReturnValue(() => returnObject);
           const fakeBazz = jest.fn();
           const wrapper = setup({ bazz: fakeBazz });
           wrapper.instance().componentDidMount();
           await expect(getStuff).toBeCalledWith(dummyData.foo, bar, fakeBazz);
           console.log(wrapper.state());
    });
Run Code Online (Sandbox Code Playgroud)

我的expect断言有效,并且getStuff使用正确的值调用了正确的断言。但getStuff返回 2 x 对象x& y- 它用于setState. 我尝试模拟 的返回值getStuff,但这些模拟的返回值未在状态中设置。

我使用mockReturnValue正确吗?

Anj*_*nja 5

你不应该将它设置在模拟函数上吗:

    fakeBazz.mockReturnValue(returnObject);
Run Code Online (Sandbox Code Playgroud)

请参阅:https ://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c