代码之家  ›  专栏  ›  技术社区  ›  Jan Bodnar

JS Jest Mocking-预期收到未定义的错误

  •  0
  • Jan Bodnar  · 技术社区  · 5 年前

    我有使用的代码 axios 获取一些数据。

    const axios = require('axios');
    
    class Users {
         static async all() {
            let res = await axios.get('http://localhost:3000/users');
            return res.data;
          }
    }
    
    module.exports = Users;
    

    这应该用jest框架进行测试。

    const axios = require('axios');
    const Users = require('./users');
    
    jest.mock('axios');
    
    test('should fetch users', () => {
    
        const users = [{
            "id": 1,
            "first_name": "Robert",
            "last_name": "Schwartz",
            "email": "rob23@gmail.com"
        }, {
            "id": 2,
            "first_name": "Lucy",
            "last_name": "Ballmer",
            "email": "lucyb56@gmail.com"
        }];
    
        const resp = { data : users };
    
        // axios.get.mockResolvedValue(resp);
        axios.get.mockImplementation(() => Promise.resolve(resp));
    
        // console.log(resp.data);
    
        return Users.all().then(resp => expect(resp.data).toEqual(users));
    });
    

    测试失败

    expect(received).toEqual(expected)
    
    Expected: [{"email": "rob23@gmail.com", "first_name": "Robert", "id": 1, "last_name": "Schwartz"}, {"email": "lucyb56@gmail.com", "first_name": "Lucy", "id": 2, "last_name": "Ballmer"}]
    Received: undefined
    

    实际数据是:

    { "users": [
        {
            "id": 1,
            "first_name": "Robert",
            "last_name": "Schwartz",
            "email": "rob23@gmail.com"
        },
        {
            "id": 2,
            "first_name": "Lucy",
            "last_name": "Ballmer",
            "email": "lucyb56@gmail.com"
        }
    ...
    ]
    }
    

    我想这可能是命名/非命名JSON数组的问题。 如何修复?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Brian Adams    5 年前

    看起来这只是一个简单的错误。

    你回来了 resp.data Users.all() 所以不用检查 响应数据 在你 expect 只要检查 resp :

    return Users.all().then(resp => expect(resp).toEqual(users));  // SUCCESS
    
    推荐文章