问题描述
我在代码中所做的只是在运行componentDidMount
之后,我正在向GitHub发出axios get请求,并将一些数据重新设置为状态.但是,当我运行测试时,它仍然说状态是一个空数组.
All I am doing in my code is upon componentDidMount
being run, I am making an axios get request to GitHub, and setting some data back onto state. However, when I run the test it still says the state is an empty array.
这是我下面的内容:
export default class HelloWorld extends Component {
constructor(props) {
super(props)
this.state = {
goodbye: false,
data: []
}
}
async componentDidMount() {
await this.func()
}
func = async () => {
let data = await axios.get('https://api.github.com/gists')
this.setState({data: data.data})
console.log(this.state)
}
goodbye = () => {
this.setState((state, currentProps) => ({...state, goodbye: !state.goodbye}))
}
render() {
return (
<Fragment>
<h1>
Hello World
</h1>
<button id="test-button" onClick={this.goodbye}>Say Goodbye</button>
{
!this.state.goodbye ? null :
<h1 className="goodbye">GOODBYE WORLD</h1>
}
</Fragment>
)
}
}
这是我的测试:
it('there is data being returned', async () => {
const component = await mount(<HelloWorld />)
component.update()
expect(component.state('data')).toHaveLength(30)
})
我对使用Jest非常陌生,不确定自己在做什么错.这个应用程序是专门为用酶测试Jest而构建的.如何正确测试此组件?
I am very new to using Jest and am not sure what I am doing wrong. This app was built solely for testing out Jest with Enzyme. How can I test this component correctly?
推荐答案
要测试从componentDidMount
运行异步功能的组件,必须先等待重新渲染,然后再运行断言. wrapper.update
用于在运行断言之前同步酶的组件树,但是不等待承诺或强制重新渲染.
Testing a component that runs an async function from componentDidMount
must await a re-render before running assertions. wrapper.update
is used to sync Enzyme's component tree before running assertions but doesn't wait for promises or force a re-render.
一种方法是使用 setImmediate
,它会在事件循环的末尾,允许承诺以非侵入方式解决.
One approach is to use setImmediate
, which runs its callback at the end of the event loop, allowing promises to resolve non-invasively.
这是您的组件的最小示例:
Here's a minimal example for your component:
import React from "react";
import Enzyme, {mount} from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({adapter: new Adapter()});
import mockAxios from "axios";
import HelloWorld from "./HelloWorld";
jest.mock("axios");
describe("HelloWorld", () => {
beforeEach(() => jest.resetAllMocks());
it("should call `axios.get` and set the response to `state.data`", async () => {
const mockData = ["foo", "bar", "baz"];
mockAxios.get.mockImplementationOnce(() => Promise.resolve({data: mockData}));
const wrapper = mount(<HelloWorld />);
await new Promise(setImmediate);
wrapper.update();
expect(mockAxios.get).toHaveBeenCalledTimes(1);
expect(wrapper.instance().state.data).toEqual(mockData);
});
});
尽管可行,但wrapper.instance().state.data
却与应用程序的内部状态联系在一起.我更愿意编写一个对行为进行断言的测试,而不是对实现进行断言的测试.变量名称的更改不应强制重写测试.
While this works, wrapper.instance().state.data
is too tied to the internal state of the application. I'd prefer to write a test that asserts on the behavior, not the implementation; variable name changes should not force tests to be re-written.
这是一个示例组件,其中更新的数据在DOM中呈现并以更黑盒的方式进行测试:
Here's an example component where the updated data is rendered in the DOM and tested in a more black-box manner:
import axios from "axios";
import React from "react";
export default class StackUsers extends React.Component {
constructor(props) {
super(props);
this.state = {users: null};
}
componentDidMount() {
this.getUsers();
}
async getUsers() {
const ids = this.props.ids.join(";");
const url = `https://api.stackexchange.com/2.2/users/${ids}?site=stackoverflow`;
const res = await axios.get(url);
this.setState({users: res.data.items});
}
render() {
const {users} = this.state;
return (
<>
{users
? <ul data-test="test-stack-users-list">{users.map((e, i) =>
<li key={i}>{e.display_name}</li>
)}</ul>
: <div>loading...</div>
}
</>
);
}
}
测试(StackUsers.test.js
):
Test (StackUsers.test.js
):
import React from "react";
import Enzyme, {mount} from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({adapter: new Adapter()});
import mockAxios from "axios";
import StackUsers from "../src/StackUsers";
jest.mock("axios");
describe("StackUsers", () => {
beforeEach(() => jest.resetAllMocks());
it("should load users", async () => {
mockAxios.get.mockImplementationOnce(() => Promise.resolve({
data: {
items: [
{"display_name": "Jeff Atwood"},
{"display_name": "Joel Spolsky"},
]
},
status: 200
}));
const wrapper = mount(<StackUsers ids={[1, 4]} />);
let users = wrapper.find('[data-test="test-stack-users-list"]');
expect(users.exists()).toBe(false);
await new Promise(setImmediate);
wrapper.update();
expect(mockAxios.get).toHaveBeenCalledTimes(1);
users = wrapper.find('[data-test="test-stack-users-list"]');
expect(users.exists()).toBe(true);
expect(users.children()).toHaveLength(2);
expect(users.children().at(0).text()).toEqual("Jeff Atwood");
expect(users.children().at(1).text()).toEqual("Joel Spolsky");
});
});
现在,测试唯一知道的是使用了axios.get
,结果应该出现在具有特定data-test
属性的元素中.这不会过度干扰CSS类,HTML结构或组件内部.
Now, the only things the test knows is that axios.get
is used and the results should appear in an element with a specific data-test
attribute. This does not unduly interfere with CSS classes, HTML structure or component internals.
作为参考,这是我的依赖项:
For reference, here are my dependencies:
}
"dependencies": {
"axios": "^0.18.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.0.3",
"redux": "^4.0.1"
},
"devDependencies": {
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"react-scripts": "^1.0.11",
"react-test-renderer": "^16.8.6"
}
}
这篇关于测试使用Jest和Enzyme更改状态的异步componentDidMount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!