I've created a very basic functional component in React (using Typescript).
However when I go to test it - I keep getting received {} when I ask it gather the divs:
So the component looks like:
export const TestComponent: React.FC<FakeInt> = () => {
return (
<div>ARE YOU WORKING
<div>Checking here</div>
</div>
)
};
along with
interface FakeInt {}
And the test:
it('It does something', () => {
let wrapper = shallow(<TestComponent />);
expect(wrapper.find("div")).toEqual("")
});
(I've just put equal to "" - as I'd expect to see something received/just want to confirm its actually finding those divs)
If I had console.log(wrapper.debug()); I actually see the wrapper's content which is strange.
The version of Jest I'm using came with my React app.
And another piece of info. expect(wrapper).toMatchSnapshot(); creates a snapshot file which also contains an empty object {}
Any ideas what's up here/why this wouldn't work?
Thanks.
please provide the version of enzyme you are using, also for react you should use enzyme-adapter-react-16 (or what ever version of react you are using)
in the test:
import { shallow, configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
than it should work
Related
I've been having an odd issue with Jest/Enzyme testing on my react typescript app. For some reason it gives a syntax error even though this is following the official documentation, as well as input from several articles.
The Code:
import React from 'react';
import NavbarTop from "../components/navbar";
import { shallow } from 'enzyme';
describe('NavbarTop', () => {
it('renders correctly', () => {
const wrapper = shallow(<NavbarTop />);
expect(wrapper).toMatchSnapshot();
// On the first run of this test, Jest will generate a snapshot file automatically.
});
});
The folder structure. I have a named class and then an index with a default export.
The error log.
Do you have JSX configured for Jest? Looks like you don't have support for JSX in Jest, which probably means this is a configuration issue. Have a look at configuring babel to support JSX in Jest.
Make sure you read this tutorial
i made a small react project with typescript
and i made it to print numbers of li tag to browser.
so i tried to implement unit test that test component create HTMLElement
but I really confused. I'm a newbie with typescript
import * as React from "react";
import { render } from "#testing-library/react";
import List from "../component/List";
describe("<List />", () => {
it("check li tags were made perfectly", async () => {
const component = render(<List />);
component.getByText("li");
});
this code's output is error at render(<List />);
my component doesn't require any props
how can i make this code is able to run properly?
Thanks to, #Edward Choupuryan
it was just simple problem.
i wanted to test react component with typescript, and that file need to has extension tsx . mine was just *.test.ts
i changed my testfile testfile.test.ts to testfile.test.tsx, and problem solved
I want to do some basic unit test to my app which I created with "create-react-app" package. I believe it already has Jest installed.
I have some basic redux code in my app.
I want to test:
It renders the main component(App.js) without crashing
Clicking to show next item funcion
I have installed Enzyme using "npm install --save-dev enzyme" and "enzyme-adapter-react-15".
Here is my code:
import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './App';
import { shallow, mount, render, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
configure({ adapter: new Adapter() });
describe('A test for App component', () => {
let wrapper
beforeEach(()=>{
wrapper = shallow(<App />);
})
it('should render App Component', () => {
expect(wrapper).to.have.length(1)
})
})
I can't get the test to start to work. The error message:
TypeError: Cannot read property 'length' of undefined
and
TypeError: Cannot read property 'have' of undefined
I think there is some basic things I am doing wrong.
Any help is appreciated!!!
You are using Jest's expect function. You need to explicitly declare the import from chai.
it will look something like:
import { expect } from 'chai'
it('should render App Component', () => {
expect(wrapper).to.have.length(1)
})
Also, instead of adding the adapter configuration for each test, you could add a file setupTests.js to /src and it will work for all tests :-)
You probably copied it from the examples on enzyme's website, which uses chai. The jest equivalent for what you're trying to test is:
it('should render App Component', () => {
expect(wrapper).toHaveLength(1)
})
I am using jest and enzyme to test my react component which relies on antd - a 3rd react UI library.
For illustrative purpose, I produce the minimal code that is fair enough to show my question.
See my test component as follow:
import React from 'react';
import { Button } from 'antd';
function Test({onSubmit}) {
return (
<div>
<Button htmlType="submit" type="primary" />
</div>
);
}
export default Test;
Q1: I mock up the Button as below since unit test requires us to isolate the target and mock up any other dependencies.
Is that correct?
__mocks__
antd.js
antd.js
import mockComponent from '../mockComponent';
const list = [
'Form',
'Input',
'Button',
'Spin',
'Icon'
];
const mockups = list.reduce((prev, next) => {
prev[next] = mockComponent(next);
return prev;
}, {});
mockups.Form.Item = mockComponent('Form.Item');
export const Form = mockups.Form;
export const Input = mockups.Input;
export const Button = mockups.Button;
export const Spin = mockups.Spin;
export const Icon = mockups.Icon;
mockComponent.js
import React from 'react';
export default function mockComponent (name) {
return props => React.createElement(name, props, props.children);
}
Q2. I have got the following warning even if the test passes. How can I resolve that?
test.spec.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';
import Test from '../components/question';
describe('mount test', () => {
let wrapper;
let props;
let mountedLogin;
const test = () => {
if (!mountedLogin) {
mountedLogin = mount(<Test {...props} />);
}
return mountedLogin;
};
beforeEach(() => {
mountedLogin = null;
});
it('always render test as the root', () => {
const divs = test().find('div');
expect(divs.length).toBeGreaterThan(0);
});
});
warning
console.error node_modules/fbjs/lib/warning.js:36
Warning: Unknown prop `htmlType` on <Button> tag. Remove this prop from the
element. For details, see
in Button (created by Unknown)
in Unknown (created by Test)
in div (created by Test)
in Test (created by WrapperComponent)
in WrapperComponent
A side note, I haven't got any jest configs in my package.json.
Can anybody help me out with these.
Many thanks
Q1: I mock up the Button as below since unit test requires us to
isolate the target and mock up any other dependencies. Is that
correct?
Currently, the recommended approach for React unit testing is shallow rendering. It basically renders the given component one level deep. If we shallow render your Test component, it will call render method of Test component, but not the render method of Button component. Even though Button is 3rd party component and dependency, we don't need to mock it. Because we don't render it. But still, we will be able to see whether it's in the component tree and it has got the correct props. This is what essentially we will assert with the mocking approach also. However, shallow rendering has few limitations also, but usually, it works very well for most of the scenarios.
But you can obviously mock children and render the whole component also. But it's time-consuming and problematic, at least with my experience.
Q2: I have got the following warning even if the test passes. How can
I resolve that?
Since you pass a string as name for React.createElement, React think you want to create a normal HTML element, and not a React component. But since there is a no HTML element call Button (case sensitive) and it doesn't know prop called htmlType, you get this unknown prop type warning. To prevent this warning, either you can stop passing props to React.createElement or pass a mock component to React.createElement instead of the name string.
import React from 'react';
function Mock(){
retun (<div/>);
}
export default function mockComponent (name) {
return props => {
return React.createElement(Mock, {...props, name}, props.children);
}
}
If you need to read more about react unit testing, I suggest you to go through this thread from react discuss forum.
Hope this helps!
I'm building unit tests with JestJS (npm jest-cli) and need to validate that a ReactJS element contains the CSS styles that I'm looking for.
I tried to check
it('should highlight the selected option in the drop-down list', function() {
var iconTriangleDown = TestUtils.findRenderedDOMComponentWithClass(dropList, 'icon-triangle-down');
var iconHeight = window.getComputedStyle(iconTriangleDown.getDOMNode(), null).height;
expect(iconHeight).notToEqual('');
});
That results in
iconHeight === ''
instead of a value of pixels.
I wonder if window is being mocked by Jest. Or if window isn't supported.
This is fairly easy using jest-dom and react-testing-library.
Tiny example:
component.js
const Component = () => <div style={{left: '4rem'}}>Left component</div>;
component.test.js
test("left shoud be 4rem", () => {
const { getByText } = render(<Component />);
expect(getByText(/left component/i).parentElement).toHaveStyle(`left: 4rem`);
})
To anyone finding this thread, Jest Enzyme now has a assert to test Styles: toHaveStyle: https://github.com/blainekasten/enzyme-matchers/blob/master/README.md#tohavestylestylekeystring-stylevalueany
The problem for me was that from seeing the code, is only testing objects and I have many styles which are arrays (I am using React Native BTW) so it was not working for me.
I am doing this method to test for a particular style:
const render = wrapper.dive();
expect(render.find("[testID='bannerStamp']").get(0).props.style[0].right).toBe(7);
You could test styles though snapshot tests, but Jest does not support evaluating component styles through assertions—that is to say through expect.
In order to do this, you need to combine Jest with enzyme, chai, and chai-enzyme.
This combination will allow you to write tests like this simple example:
it('should render style', () => {
chai.expect(shallow(
<div
style={{
left: '4rem'
}}
/>
)).to.have.style('left', '4rem');
});
First, create a setup file and add it to the the jest.setupFiles array in package.json. See the Jest documentation for an overview of this option.
This is my setup file:
// test/setup.js
import React from 'react';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow, render, mount } from 'enzyme';
// Add commonly used methods and objects as globals
global.chai = chai;
global.mount = mount;
global.React = React;
global.render = render;
global.shallow = shallow;
chai.use(chaiEnzyme());
This is my package.json:
{
"jest": {
"setupFiles": [
"./test/setup.js"
]
}
}
Now, when necessary, you are able to access the Chai assertions API through chai.expect and the Jest assertions API through expect.