I am getting error while testing axios.get function in react
here is my code
https://codesandbox.io/s/oq7kwzrnj5
it("check ajax call", () => {
jest.mock('axios', () => {
const exampleArticles:any = {
data :{
data:['A','B','c']
}
}
return {
get: jest.fn(() => Promise.resolve(exampleArticles)),
};
});
expect(axios.get).toHaveBeenCalled();
});
any update ?? no solution
I've found this information in jest-mock-axios:
Why do we need to manually create the mock?
It's because Jest expects mocks to be placed in the project root,
while packages
installed via NPM get stored inside node_modules subdirectory.
Maybe that's why you can't use jest.mock and there are packages like above to solve that.
Related
I'm struggeling to understand how to test the renderer - main interactions for my electron app.
I setup my electron App using the electron-react-template. In my preload.ts file I define a callback, so I can tell the component can listen when some data was loaded
contextBridge.exposeInMainWorld("api", {
file: {
wasOpened: (callback) => { return ipcRenderer.on('api-file-wasOpened') }
}
})
In my component I listen to the event like this
function App(){
const [isStorageOpen, setIsStorageOpen] = useState(false);
api.file.wasOpened((event, value) => {
setIsStorageOpen(true);
})
return (
<div>Storage is open: {isStorageOpen}</div>
)
}
My testfile is just a very simple check if the component renders for now
describe('App', () => {
it('should render', () => {
expect(render(<App />)).toBeTruthy();
});
});
When I start the App (npm run start) it does not throw any errors, and the api is defined. However, when I run it as a test (with jest) I get the error that api is undefined (ReferenceError: api is not defined).
My question is, do I need to do something special to have the api loaded during testing or should I just mock it? If so, how would I mock the functions that I use to communicate from main to the renderer, and how would I send the ipcRenderer.invoke signal?
I'm developing react native app, in that i'm using two packages for exiting and restarting my app.
Whenever I tries to mock these functions in getting error. I'm not able to cover test cases for exit and restart methods
Could anybody know how do we mock these functions
import RNRestart from 'react-native-restart';
import RNExitApp from 'react-native-exit-app';
if (configNotThere) {
RNExitApp.exitApp();
}
if(configFound){
RNRestart.Restart();
}
Jest code
jest.mock('react-native-exit-app', () => ({
RNExitApp: {
exitApp: () => jest.fn(),
},
}));
expect(exitApp).toHaveBeenCalledTimes(1);
// expect(RNExitApp.exitApp()).toHaveBeenCalledTimes(1);
// beforeEach(() => {
// const exitAppMockValue = jest.fn();
// exSpy.mockReturnValue(exitAppMockValue);
// });
// const dummyExit = jest.fn();
// rnExitMock.mockReturnValue(dummyExit);
// RNExitApp.exitApp().mockResolvedValueOnce();
// const component = shallow(<KfcAppError />);
// component.find(TouchableOpacity).forEach((element) => {
// element.simulate('press');
// });
// RNExitApp.exitApp().mockResolvedValueOnce(true);
tried with all the way BUT no luck for always some of the getting errors
How to mock npm package methods in jest ?
Please anybody help me on this
react native exit app npm package
react native restart app npm package
I have come up with below answer for mocking npm module methods
In setup.js file we need to declare the methods like below then it will detect the methods in any of test.js files
jest.mock('react-native-exit-app', () => ({
exitApp: () => jest.fn(),
}));
I was experimenting with tRCP and diligently followed the setup for my Next.js project described in the official docs over here: https://trpc.io/docs/nextjs
However I noticed that a simple component that relies on tRPC such as this
export const Sample = () => {
const { data } = trpc.useQuery(['hello', { text: 'User' }]);
if (data === undefined) {
return <div>Loading...</div>;
}
return <div>{data.greeting}</div>;
};
cannot be properly tested since the following trivial test
describe('Sample', () => {
it('should render successfully', () => {
const { baseElement } = render(<Sample />);
expect(baseElement).toBeTruthy();
});
});
since there is no setup of provider such as the setup with the withTRCP HOC used for the application itself. As such the test fails claiming client (presumably the trcpClient, unlike the queryClient) is undefined.
I'd like to know how to setup the test correctly, in this case providing a correct client, as well as mocking the queries, since I don't have the respective server-side code running while invoking the tests.
Since you are getting undefined for the trpc client implementation, you can try spying on the query call.
import trpc from 'utils/trpc'; // This is the client implementation
describe('Sample', () => {
it('should render successfully', () => {
jest.spyOn(trpc, 'useQuery')
.mockReturnValue({ greeting: "Greeting" });
const { baseElement } = render(<Sample />);
expect(baseElement).toBeTruthy();
});
});
This is also possible with the mutations but you need to provide a mock implementation for the useMutation response for mutate property.
I'm getting a strange error when trying to use react-testing-library to test React.Suspense. The error just says "Not Supported" but doesn't give any real insight into the problem. I followed the example that Kent Dodds did on youtube.
I posted the full code of my problem on github here, but here's a snapshot of the test code:
import React from "react";
import { render, waitForElement, cleanup } from "react-testing-library";
import MyOtherPackageThing from "my-package/lib/my-thing";
import LazyThing from "../src/index";
afterEach(cleanup);
test("it works", async () => {
const { getByText, debug } = render(<MyOtherPackageThing />);
await waitForElement(() => getByText("my thing"));
expect(getByText("my thing"));
});
describe("these fail with 'Not Supported'", () => {
test("it lazy loads a local component", async () => {
const LazyLocalThing = React.lazy(() => import("../src/LocalThing"));
const { getByText, debug } = render(
<React.Suspense fallback="Loading...">
<LazyLocalThing />
</React.Suspense>
);
debug();
await waitForElement(() => getByText("my local thing"));
debug();
expect(getByText("my local thing"));
});
test("it says not supported, like wtf", async () => {
const { getByText, debug } = render(<LazyThing />);
debug();
await waitForElement(() => getByText("my thing"));
debug();
expect(getByText("my thing"));
});
});
I encountered the same error recently. I noticed that Kent's working sample was using create-react-app and wondered if it was Babeling something special for Node/Jest. As a result of using CRA, his package.json uses the babel preset react-app.
Try installing and configuring the plugin babel-plugin-dynamic-import-node (which is the specific part of the react-app preset I think we need). I believe this plugin transforms dynamic imports into require statements for Node. More info: https://www.npmjs.com/package/babel-plugin-dynamic-import-node
install the plugin:
npm i --save-dev babel-plugin-dynamic-import-node
in my-consumer-pkg/babel.config.js, add the plugin:
plugins: [
...
"babel-plugin-dynamic-import-node"
]
...this should be enough to get past the Not Supported error.
As an aside, I noticed that one of your tests named "it lazy loads a local component" was subsequently failing with this error:
Element type is invalid. Received a promise that resolves to: [object Object]. Lazy element type must resolve to a class or function.
...so I made a minor change so that the LocalThing was a function
const LocalThing = () => <div>my local thing</div>;
I'm trying to mock out methods in an imported module while testing a separate module. I'm able to successfully mock the imported module with ES2015 import syntax, but the mock stays consistent throughout the entire test and there are instances where I'd like to change the mock.
My files look like this
// ModuleA
import ModuleB from 'ModuleB'
// ... code
// TestCase
import ModuleA from 'ModuleA'
import ModuleB from 'ModuleB'
jest.mock('ModuleB', () => {
return {
value: true
}
}
describe('ModuleA', () => {
it('returns true', () => {
// This test expects ModuleB.value to return true
});
it('returns false', () => {
// This doesn't work
ModuleB.value = jest.fn(() => false)
// This doesn't work either
jest.mock('ModuleB', () => {
return {
value: false
}
});
// This test expects ModuleB.value to return false in order to pass
});
});
I essentailly need to separate mocks for ModuleB. In the past, I've been able to simply use var ModuleB = require('ModuleB'); instead of import and then call ModuleB.someMethodName = jest.fn() whenever needed. I'd like to use only ES2015 for these tests though, and using the pattern I just mentioned gives me a ModuleB is read-only error.
Use the requireActual method:
To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using require.requireActual(moduleName) in your manual mock and amending it with mock functions before exporting it.
For example:
const RealModule = require.requireActual('Form');
const MyModule = {
RealThing: RealModule.RealThing,
…add some mocks
};
References
jest.js Issue #1557: How to mock just the React components from a module exporting many things
jest.js Issue #1273: require.requireActual not returning the actual mock
Troubleshooting · Jest