javascript - 测试用例失败

标签 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函数、contentApiid 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' }

最佳答案

你的 mockend fetch 函数仍然是异步的(它返回一个 Promise)所以你仍然必须“等待”它才能访问“已加载”的数据。

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

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

当然,您必须告诉 Jest 等待异步代码,因此您还需要return obj.fetchContent()...

关于javascript - 测试用例失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52185396/

相关文章:

javascript - 如果在 uib-tabset 中使用,则值不与范围的变量绑定(bind)

javascript - Firebase 查询子级的子级是否包含值

javascript - "trampoline"方法之间的区别

reactjs - 即使在执行 fetch.mockResponse 之后仍使用 Jest 实际获取被调用

electron - 如何在 Electron 应用程序中包含模板组件的分布

javascript - 如何使用一个函数用对象替换数组中的多个特定字符串?

testing - 如何不到处放 "use strict"

node.js - Jest 检查设置是对还是错

css - Stenciljs CSS 全局变量

javascript - Stencil.js : How to use utils function in index. html