admin管理员组

文章数量:1300026

I come again asking for help with jest. The scenario is a bit complicated, I think:

  • I have a an API class (BaseApi) whose contructor return a Proxy to wrap a set of Rest calls
    • This class has a manual mock
  • I have another file, where this class is initialized on the file level
    • This API proxy-ed methods (get and post mostly) are called in functions on this file
  • I want to change the return of the proxied method on at least one of my tests
// auth/base.js
class BaseApi {
    constructor() {
        return new Proxy(this, {
            get(api, calledProp, receiver) {
                const reflectedProp = Reflect.get(api, calledProp, receiver);
                const fetchCalls = ['post', 'delete', 'get', 'patch'];

                if (fetchCalls.indexOf(calledProp) >= 0) {
                    return (...args) => api.apiCall(calledProp.toUpperCase(), ...args);
                }

                return reflectedProp;
            },
        });
    }
    async apiCall(method, endpoint, headers, queryParams, body = null) {
        //implementation ...
    }
}

module.exports = { BaseApi };
// auth/__mocks__/base.js
class BaseApi {
    apiCall = jest.fn().mockImplementation(method, endpoint, headers, queryParams, body = null)

    get = jest.fn().mockResolvedValue({
        ok: false,
    });
}

module.exports = { BaseApi };
// main/index.js
const { BaseApi } = require('../auth/base');
const baseApi = new BaseApi();

// ... more stuff
const processRequest = async function() {
    const processCall = await baseApi.get(route, headers);

    if (processCall.ok) {
        return 'Success'
    } else {
        return null
    }
}

module.exports = { processRequest };
// main/index.test.js
jest.mock('../auth/base');
const { BaseApi } = require('../auth/base');
const { processRequest } = require('./index');

describe('process', () => {
    it('correct based on the global mock', async () => { // this is working as expected
        const result = await processRequest();
        expect(result).toBe(null);
    });

    it('this test is erro-ing', async () => {
        /*
          This fails with the following message:     Property `get` does not exist in the provided object
         */
        jest.spyOn(BaseApi, 'get').mockResolvedValueOnce({ ok: true });
        const result = await processRequest();

        expect(result).toBe('Success');
    });
});

So, my question is, how can I change the return of a method of a manual mocked class on a specific test?

本文标签: javascriptHow to change the implementation of on method of a global mocked class on jestStack Overflow