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(),
}));
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 try to make a snapshot testing using react-test-renderer, I need to render a component which use the code below (in a separate file) to conditionally render different component.
let mql = window.matchMedia("(max-width: 600px)");
let mobileView = mql.matches;
export default mobileView;
This is the snapshot test
test("Your test case", () => {
const component = renderer.create(<CalendarTitle month={8} year={2021} />);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
I have tried using jest-matchmedia-mock package but it can't solve the problem, maybe it need to mock in a different file but i am not sure what to write in matchMedia.mock.ts file and what is the myMethod from "file-to-test" and how to write to complete test method.
import matchMedia from './matchMedia.mock.ts'; // Must be imported before the tested file
import { myMethod } from './file-to-test';
describe('myMethod()', () => {
// Test the method here...
});
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 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.
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