我正在尝试使用 jest 测试以下功能:
fetchContent() {
fetch(`${this.contentApi}?id=${this.id}`)
.then(data => data.json())
.then(response => {
this.content = response;
console.log('===this.content====', this.content);
console.log('===Response====', response);
console.log('===This====', this);
this.assignContent();
})
.catch(error => {
throw Error(error);
});
}
为了编写这个函数的测试用例,我模拟了window.fetch
函数contentApi
、id
和assignContent
函数。然后,我尝试通过模拟所有必要的函数和变量来在我的测试用例中调用这个函数。
这是测试用例的片段:
it('should fetch and assign content', () => {
obj.assignContent = jest.fn();
obj.contentApi = 'abc.xyz';
obj.id = 'dxp';
window.fetch = jest.fn().mockImplementation(url => {
if(url === 'abc.xyz?id=dxp') {
return Promise.resolve({
json: () => { return 'abc'; }
})
}
else {
return Promise.reject(new Error());
}
});
obj.fetchContent();
console.log('===OBJ====', obj);
// expect(obj.content).toEqual('abc');
// expect(obj.assignContent).toBeCalled();
});
它失败了,既没有将内容设置为'abc'
,也没有在调用assignContent()
。
console.log src\dxp-container.spec.tsx:57
===OBJ==== Container {
initialAssignmentDone: false,
assignContent:
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockReturnValueOnce: [Function],
mockReturnValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockRestore: [Function] },
contentApi: 'abc.xyz',
id: 'dxp' }
console.log src\dxp-container.tsx:24
===this.content==== abc
console.log src\dxp-container.tsx:25
===Response==== abc
console.log src\dxp-container.tsx:26
===This==== Container {
initialAssignmentDone: false,
assignContent:
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockReturnValueOnce: [Function],
mockReturnValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockRestore: [Function] },
contentApi: 'abc.xyz',
id: 'dxp',
content: 'abc' }