kar*_*017 5 javascript mocking jestjs react-testing-library
我的组件 useEffect 钩子中有这个函数链。我将响应/数据设置为我的组件状态,以便我可以在我的组件中呈现数据。
client
.items()
.type("client")
.toObservable()
.subscribe(response => {
setState(response)
})
Run Code Online (Sandbox Code Playgroud)
我如何模拟这个函数并在组件在我的测试中呈现之前调用它?我正在使用测试库/反应。
回应是
{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 };
Run Code Online (Sandbox Code Playgroud)
client.ts在反应组件中使用模块:
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 };
Run Code Online (Sandbox Code Playgroud)
单元测试,真实client.ts模块的模拟链方法,将模拟模块注入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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
单元测试结果:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4305 次 |
| 最近记录: |