1

我正在尝试使用 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函数contentApiidassignContent函数。然后,我尝试通过模拟所有必要的函数和变量来在我的测试用例中调用这个函数。

这是测试用例的片段:

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' }
4

1 回答 1

1

您的 mockendfetch函数仍然是异步的(它返回一个 Promise),因此您仍然必须“等待”它才能访问“加载”的数据。

fetchContent() {
    return fetch(`${this.contentApi}?id=${this.id}`)
    ...
}

obj.fetchContent().then(() => {
   console.log('===OBJ====', obj);
})

当然,您必须告诉 Jest 等待异步代码,所以您也需要return obj.fetchContent()....

于 2018-09-05T13:29:51.990 回答