admin管理员组文章数量:1307220
I have the configuration of a service inside a ponent in React and I am having problems with jest and testing-library, the app is working but the test is blocking.
import { appSetupConfig } from '.../myapp'
import theConfig from '.../config'
useEffect(() => {
const allowAppInstance = appSetupConfig();
allowAppInstance.get(theConfig).then((value) => {
if (value.something) {
Do Something;
}
...the rest of code
}, []);
This theConfig is an external file containing an object. This is the error:
TypeError: Cannot read property 'get' of undefined
37 | const allowAppInstance = appSetupConfig();
38 |
> 39 | allowAppInstance.get(theConfig).then((value) => {
Is there any way to mock this get in jest's setup.js? I don’t necessarily need to test this item yet, but I can’t proceed without it.
I have the configuration of a service inside a ponent in React and I am having problems with jest and testing-library, the app is working but the test is blocking.
import { appSetupConfig } from '.../myapp'
import theConfig from '.../config'
useEffect(() => {
const allowAppInstance = appSetupConfig();
allowAppInstance.get(theConfig).then((value) => {
if (value.something) {
Do Something;
}
...the rest of code
}, []);
This theConfig is an external file containing an object. This is the error:
TypeError: Cannot read property 'get' of undefined
37 | const allowAppInstance = appSetupConfig();
38 |
> 39 | allowAppInstance.get(theConfig).then((value) => {
Is there any way to mock this get in jest's setup.js? I don’t necessarily need to test this item yet, but I can’t proceed without it.
Share Improve this question asked May 29, 2021 at 23:32 CodeGCodeG 4672 gold badges6 silver badges18 bronze badges1 Answer
Reset to default 5Yes, there is. So it would seem that you have called jest.mock('.../myapp')
or similar at some point. In the mock object that Jest creates for the module, every mock function returns undefined
. You need to mock a return value on appSetupConfig
that is itself a mock object with the method(s) you need like get
. Then get
in turn needs to return a mock promise, and so on as deeply as needed. In your setup file, this would look like:
import { appSetupConfig } from '.../myapp'
...
jest.mock('.../myapp');
appSetupConfig.mockReturnValue({
get: jest.fn().mockResolvedValue({ something: jest.fn() }),
});
Your .then
block will then be called in the test(s) with value
set to undefined
, but you can mock a different resolved value or a rejection of the promise for particular tests.
本文标签: javascriptJest errorCannot read property 39get39 of undefinedStack Overflow
版权声明:本文标题:javascript - Jest error -- Cannot read property 'get' of undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741834724a2400145.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论