gpt4 book ai didi

javascript - 如何用 jest 模拟和测试链式函数?

转载 作者:行者123 更新时间:2023-12-03 22:04:49 26 4
gpt4 key购买 nike

我的组件 useEffect Hook 中有这个函数链。
我将响应/数据设置为我的组件状态,以便我可以在我的组件中呈现数据。

client
.items()
.type("client")
.toObservable()
.subscribe(response => {
setState(response)
})

我如何模拟这个函数并在组件在我的测试中呈现之前调用它?我正在使用测试库/ react 。

回应是 {items: [{},...]}, somethingElse: {}

最佳答案

您可以使用mockFn.mockReturnThis()去做这个。client.ts , 模拟真实的第三方模块

const client = {
items: () => {
return client;
},
type: (name: string) => {
return client;
},
toObservable: () => {
return client;
},
subscribe: handler => {
handler();
return client;
}
};

export { client };

使用 client.ts react 组件中的模块:
class Component {
private props;
constructor(props) {
this.props = props;
}
public componentDidMount() {
this.props.client
.items()
.type('client')
.toObservable()
.subscribe(response => {
this.setState(response);
});
}
private setState(state) {
console.log(state);
}
}

export { Component };

单元测试,真实的mock链方法 client.ts模块,注入(inject)模拟的 client模块到您的组件中。
import { Component } from './';

const mockClient = {
items: jest.fn().mockReturnThis(),
type: jest.fn().mockReturnThis(),
toObservable: jest.fn().mockReturnThis(),
subscribe: jest.fn().mockReturnThis()
};

const mockProps = {
client: mockClient
};

const component = new Component(mockProps);

describe('Component', () => {
describe('#componentDidMount', () => {
it('should mount the component and set state correctly', () => {
const mockedResponse = { items: [{}], somethingElse: {} };
mockClient.subscribe.mockImplementationOnce(handler => handler(mockedResponse));
// tslint:disable-next-line: no-string-literal
component['setState'] = jest.fn();
component.componentDidMount();
expect(mockClient.items().type).toBeCalledWith('client');
// tslint:disable-next-line: no-string-literal
expect(component['setState']).toBeCalledWith(mockedResponse);
});
});
});

单元测试结果:
 PASS  src/mock-function/57719741/index.spec.ts
Component
#componentDidMount
✓ should mount the component and set state correctly (6ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.542s, estimated 2s

关于javascript - 如何用 jest 模拟和测试链式函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57719741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com