测试用例失败

时间:2018-09-05 12:41:10

标签: javascript jestjs stenciljs

我正在尝试使用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' }

1 个答案:

答案 0 :(得分:1)

您的模拟对象mysql --version 函数仍然是异步的(它返回一个Promise),因此您仍然需要“等待”它,然后才能访问“已加载”的数据。

fetch

当然,您必须告诉Jest等待异步代码,因此您还需要fetchContent() { return fetch(`${this.contentApi}?id=${this.id}`) ... } obj.fetchContent().then(() => { console.log('===OBJ====', obj); })