简体   繁体   English

试图用玩笑制作一个简单的 Axios 模拟

[英]Trying to make a simple Axios mock with jest

I am trying to understand this example , so the first thing I am trying is removing his axiosConfig.js , so the example looks more like the current case I would like to solve.我试图理解这个例子,所以我尝试的第一件事是删除他的axiosConfig.js ,所以这个例子看起来更像是我想要解决的当前案例。 However I get this error但是我收到这个错误

- Expected
+ Received

  Object {
+   "baseURL": "https://jsonplaceholder.typicode.com/albums",
    "method": "get",
    "url": "/3/photos?_limit=3",
  },

Number of calls: 1

  39 |         const photos = await getPhotosByAlbumID(3);
  40 |         expect(axios.request).toHaveBeenCalled();
> 41 |         expect(axios.request).toHaveBeenCalledWith({ method: 'get', url: '/3/photos?_limit=3' })
     |                               ^
  42 |         expect(photos.length).toEqual(3);
  43 |         expect(photos[0].albumId).toEqual(3)
  44 |     });

Question

Can anyone figure out how to fix the failed test?谁能弄清楚如何修复失败的测试?

If I remove baseURL: 'https://jsonplaceholder.typicode.com/albums' from getPhotosByAlbumId() , but it doesn't make sense to have axios.request() without a baseURL .如果我从getPhotosByAlbumId()删除baseURL: 'https://jsonplaceholder.typicode.com/albums' ,但没有axios.request()没有baseURL

I have it online at https://repl.it/@SandraSchlichti/jest-playground#index.js我在https://repl.it/@SandraSchlichti/jest-playground#index.js在线

index.js索引.js

const axios = require('axios');

const getPhotosByAlbumId = async (id) => {
    const result = await axios.request({
      baseURL: 'https://jsonplaceholder.typicode.com/albums',
      method: 'get',
      url: `/${id}/photos?_limit=3`
    });
    const { data } = result;
    return data;
};

module.exports = getPhotosByAlbumId;

index.spec.js index.spec.js

const axios = require('axios');
const getPhotosByAlbumID = require('./index');

jest.mock('axios', () => {
    return {
        baseURL: 'https://jsonplaceholder.typicode.com/albums',
        request: jest.fn().mockResolvedValue({
            data: [
                {
                    albumId: 3,
                    id: 101,
                    title: 'incidunt alias vel enim',
                    url: 'https://via.placeholder.com/600/e743b',
                    thumbnailUrl: 'https://via.placeholder.com/150/e743b'
                },
                {
                    albumId: 3,
                    id: 102,
                    title: 'eaque iste corporis tempora vero distinctio consequuntur nisi nesciunt',
                    url: 'https://via.placeholder.com/600/a393af',
                    thumbnailUrl: 'https://via.placeholder.com/150/a393af'
                },
                {
                    albumId: 3,
                    id: 103,
                    title: 'et eius nisi in ut reprehenderit labore eum',
                    url: 'https://via.placeholder.com/600/35cedf',
                    thumbnailUrl: 'https://via.placeholder.com/150/35cedf'
                }
            ]
        })
    }
})

describe('test getPhotosByAlbumID ', () => {
    afterEach(() => jest.resetAllMocks());

    it('fetches photos by album id', async () => {
        const photos = await getPhotosByAlbumID(3);
        expect(axios.request).toHaveBeenCalled();
        expect(axios.request).toHaveBeenCalledWith({ method: 'get', url: '/3/photos?_limit=3' })
        expect(photos.length).toEqual(3);
        expect(photos[0].albumId).toEqual(3)
    });
});

Since in your implementation you're calling axios.request with an object that has baseURL, it doesn't matches your assertion.由于您实现你打电话axios.request与具有一个基本URL对象,它不符合你的说法。

So you can either assert that it has to be called with an object that has baseURL因此,您可以断言必须使用具有 baseURL 的对象调用它

expect(axios.request).toHaveBeenCalledWith({
    baseURL: "https://jsonplaceholder.typicode.com/albums",
    method: "get",
    url: "/3/photos?_limit=3",
});

or that the object the method has been called with has to have these two properties:或者调用该方法的对象必须具有以下两个属性:

expect(axios.request).toHaveBeenCalledWith(
    expect.objectContaining({ method: "get", url: "/3/photos?_limit=3" })
);

working example 工作示例

I'll recommend U to use Asymmetric Matchers我会推荐你​​使用非对称匹配器

 expect(axios.request).toHaveBeenCalledWith(
  expect.objectContaining({
    method: 'get',
    url: '/3/photos?_limit=3'
  }))

Sometimes you have a big object and is not necessary to match the exact object you can choose which ones you want to compare.有时您有一个很大的对象,不需要匹配确切的对象,您可以选择要比较的对象。

Another example could be:另一个例子可能是:

expect(mock).toHaveBeenCalledWith(expect.objectContaining({
  postalCode: expect.any(Number)
}));

here your example working https://repl.it/join/ldayfmqz-yoandrycollazo这里你的例子工作https://repl.it/join/ldayfmqz-yoandrycollazo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM