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
andpost
mostly) are called in functions on this file
- This API proxy-ed methods (
- 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?
版权声明:本文标题:javascript - How to change the implementation of on method of a global mocked class on jest? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741632727a2389460.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论