angular-mocks giving me a module error when testing a component - angularjs

I'm receiving the following error when trying to test a component with angularJS. This component is part of a library I've created with this language and uses Jest instead of Jasmine.
TypeError: angular_1.default.mock.module is not a function
6 | describe('Badge', () => {
7 | beforeEach(() => {
> 8 | angular.mock.module(['myApp.components.quoteCard']);
| ^
9 | });
10 | it('renders badge', () => {
11 | render(`
This is the test code following the specifities:
import angular from 'angular';
import 'angular-mocks';
import { render, screen } from 'angularjs-testing-library';
import './quote-card';
describe('Badge', () => {
beforeEach(() => {
angular.mock.module(['myApp.components.quoteCard']);
});
it('renders badge', () => {
render(`
<quote-card-component
content="content"
author="author"
></quote-card-component>
`);
expect(screen.getByText(`content`)).toBeInTheDocument();
});
});
If someone knows how to solve this, it would be great. Thanks folks!

Angular mocks works only with Jasmine or Mocha. Theres a strict condition inside the library. So you need to setup a global variable before running your tests.
For example
global.mocha = true;

Related

I trying to unit test my work, somehow waitfor isn't working? It's timing out

I have a unit test, I've already mocked my fetchAppList and fetchTotalAppCount but somehow when I try to render my component, but I keep getting this error:
● loads the correct number of apps
Timed out in waitFor.
11 | render(<IntegrationsPage/>);
12 |
> 13 | const appList = await waitFor(() => screen.findAllByText("Notify me when it's ready"));
| ^
14 | expect(appList).toHaveLength(10);
15 | });
at waitForWrapper (node_modules/#testing-library/dom/dist/wait-for.js:187:27)
at Object.<anonymous> (src/pages/integrations/IntegrationsPage.test.js:13:34)
This is what my test looks like:
import { render, screen, waitFor } from "#testing-library/react";
import IntegrationsPage from "./IntegrationsPage";
import apps from "../../api/apps/Apps";
import mockData from "../../api/apps/MockData";
jest.mock("../../api/apps/Apps");
test("loads the correct number of apps", async() => {
apps.fetchAppList.mockResolvedValue(mockData);
apps.fetchTotalAppCount.mockImplementation(() => mockData.length);
render(<IntegrationsPage/>);
const appList = await waitFor(() => screen.findAllByText("Notify me when it's ready"));
expect(appList).toHaveLength(10);
});
The integrationsPage is using useEffect to render a list of apps. Each app has a link that says Notify me when it's ready in another child component.
useEffect(() => {
const totalAppCount = Apps.fetchTotalAppCount()
const pageCount = calculatePageCount(totalAppCount);
Apps
.fetchAppList(INITIAL_OFFSET,ITEMS_PER_PAGE)
.then((result) => {
setCurrentPage(INITIAL_PAGE);
setTotalAppCount(totalAppCount);
setPageCount(pageCount);
setAppList(result);
});
},[]);

React testning library Undefined property in component

I dont understand why the property of the component is breaking the test?
Do i have to pass the component the properties? Even if i do pass the props i still get the same error.
I dont want to test implementation details.
Thanks in advance!
Here is my code:
it("render correctly", () => {
const { getByTestId } = render(<CalendarAvailability />);
const date = getByTestId("date");
expect(date).toBeInTheDocument();
})
The Component:
import {Availability, AvailableDate, Status, AvailableDateContainer} from './CalendarAvailability.css'
function CalendarAvailability({unitData}) {
return(
<Availability data-testid="calendar-availability-component">
<AvailableDateContainer>
<AvailableDate data-testid="date">{unitData.date}</AvailableDate>
</AvailableDateContainer>
</Availability>
)
}
export default CalendarAvailability;
The failing test:
● <CalendarAvailability /> › renders without breaking
TypeError: Cannot read property 'date' of undefined
5 | <Availability data-testid="calendar-availability-component">
6 | <AvailableDateContainer>
> 7 | <AvailableDate data-testid="date">{unitData.date}</AvailableDate>
| ^
8 | </AvailableDateContainer>
9 | </Availability>
I dont want to test the props only the rendring of the div?

React Testing Library Mock function not called

I am pretty new to testing and attempting to write what should be a simple test for our project...
test('Attempt Login', async () => {
const submitHandler = jest.fn( ()=> console.log('hello'))
const { debug, getByText, getByTestId, getByPlaceholderText } = render
(
<Router>
<LoginPage submitHandler={submitHandler} />
</Router>
)
fireEvent.change(getByPlaceholderText("Enter Username"), {
target: { value: "admin" }
});
fireEvent.change(getByPlaceholderText("Enter Password"), {
target: { value: "Password" }
});
fireEvent.click(getByTestId("login-btn"));
expect(submitHandler).toHaveBeenCalled()
})
My button inside of login
<Button data-testid="login-btn" type="submit" variant="contained" color="primary"
onClick={(event)=>submitHandler(event)}>
the testing error
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
45 | fireEvent.click(getByTestId("login-btn"));
46 |
> 47 | expect(submitHandler).toHaveBeenCalled()
| ^
48 | })
49 |
50 |
Thanks in advance for any help. I spent way too long on this already -_-
EDIT: attempting to test for the results of clicking the login button
Heres what I'm going trying:
mock an Axios call to the login route
await waitForElement getByText('home')
expect getbytext('home')
Am I on the right track?
Do I need to import the redirect page component and place it inside the router? for example the component for it to redirect to it?
You should use waitFor in this case:
...
await waitFor(() => expect(submitHandler).toHaveBeenCalled())
...
More info HERE
As you already figured out, the problem is you are passing the submitHandler mock into LoginPage but you are not using that prop.
To answer your second question
How do I mock a function not passed in as a prop?
Here is how you can mock functions imported from different files with Jest:
import { submitForm } from './ajax.js'; // the function to mock
jest.mock('./ajax.js'); // jest mocks everything in that file
it('should call submitForm correctly', async () => {
submitForm.mockResolvedValue({ loggedIn: true });
render(<LoginPage />);
userEvent.click(screen.getByRole('button', { name: 'Login' }));
expect(submitForm).toHaveBeenCalledTimes(1);
expect(await screen.findByText('You have logged in successfully')).toBeInTheDocument();
});
Useful links
Mocking modules
Understanding Jest mocks
mockResolvedValue

Jest, Enzyme test failing on window variable undefined

I'm trying to create a window object to pass to my tests that includes a window variable. The test looks like:
const baseProps = {};
Enzyme.configure({ adapter: new Adapter() });
const baseWrapper = shallow(
<DivisionOrderIndex {...baseProps} />,
);
describe('<DivisionOrderIndex />', () => {
test('renders the MsDataGridServer', () => {
expect(baseWrapper.find(MsDataGridBulkDelete))
.toHaveLength(1);
});
The error message I receive is:
TypeError: Cannot read property 'read_only' of undefined
300 | </TitleButton>
301 | </div>
> 302 | {!window.jsdata.read_only && (
| ^
303 | <div id="page-buttons">
304 | Create New
305 | </div>
I've tried adding that data to my window object like so:
describe('<DivisionOrderIndex />', () => {
Object.defineProperty(window, 'jsdata', {
read_only: false,
});
test('renders the MsDataGridServer', () => {
expect(baseWrapper.find(MsDataGridBulkDelete))
.toHaveLength(1);
});
But I continue to get the same error. Is this the correct way to pass both the window object or the variables? Any input would be appreciated.
That's not how you add a property to an object. What you're doing here is adding a descriptor property that describes your object, there are only a few of them that you can set here e.g. writable, configurable etc.
You need to mock window object in the setupTests.js file like this:
window.jsdata = {
read_only: false
}

React Native Jest Syntax Error: Unterminated Regular Expression

I'm getting this strange syntax error whilst running a simple test for a Todo demo I'm writing. I have added the code and test in the same file so that you can see what's going on.
Any help will be greatly appreciated.
import { Text } from 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
const TodoItem = () => {
return(
<Text>{Hello}</Text>
);
};
export default TodoItem;
describe('<TodoItem', () => {
it('should update uncompleted task to complete when pressed', () => {
const wrapper = shallow(<TodoItem />)
});
});
Test Result
Run: jest
FAIL __tests__/components/TodoItem.spec.tsx
● Test suite failed to run
SyntaxError: /Users/jonesagyemang/Projects/side/Todoist/__tests__/components/TodoItem.spec.tsx: Unterminated regular expression (7:19)
5 | const TodoItem = () => {
6 | return(
> 7 | <Text>{Hello}</Text>
| ^
8 | );
9 | };
10 |
at Object.raise (../../../../../usr/local/lib/node_modules/jest/node_modules/#babel/parser/lib/index.js:6322:17)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.2s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
I'm assuming it's a text that you want to display with Text component. Try removing the {} for the Hello since it isn't a variable or a function in your code.
const TodoItem = () => {
return(
<Text>Hello</Text>
);
};

Resources