我正在研究[故事书]教程,但使用Material-UI
作为UI框架。
我已经完成了我有可用的Task
和TaskList
组件的程度。 我开始使用Jest
和enzyme
编写测试,这就是事情开始动摇的地方。
我的测试看起来像
import React from "react";
import ReactDOM from "react-dom";
import TaskList from "./TaskList";
import { withPinnedTasks } from "../../stories/TaskList.stories";
import { MuiThemeProvider } from "@material-ui/core";
import { theme } from "../theme";
import { createMount } from "@material-ui/core/test-utils";
describe("SearchField", () => {
let mount;
beforeEach(() => {
mount = createMount();
});
afterEach(() => {
mount.cleanUp();
});
it("renders pinned tasks at the start of the list", () => {
const div = document.createElement("div");
const events = { onPinTask: jest.fn(), onArchiveTask: jest.fn() };
let wrapper = mount(
<MuiThemeProvider theme={theme}>
<TaskList tasks={withPinnedTasks} {...events} />
</MuiThemeProvider>
);
console.log(wrapper);
// We expect the task titled "Task 6 (pinned)" to be rendered first, not at the end
const lastTaskInput = wrapper.find('#id').to.have.lengthOf(1);
// querySelector(
// '.list-item:nth-child(1) input[value="Task 6 (pinned)"]'
// );
expect(lastTaskInput).not.toBe(null);
ReactDOM.unmountComponentAtNode(div);
});
});
当我运行yarn test
时,它失败并显示以下错误
● SearchField › renders pinned tasks at the start of the list
TypeError: Cannot read property 'have' of undefined
30 |
31 | // We expect the task titled "Task 6 (pinned)" to be rendered first, not at the end
> 32 | const lastTaskInput = wrapper.find('#id').to.have.lengthOf(1);
| ^
33 |
34 | // querySelector(
35 | // '.list-item:nth-child(1) input[value="Task 6 (pinned)"]'
at Object.it (src/components/TaskList.test.js:32:27)
整个代码库可在 https://codesandbox.io/s/github/hhimanshu/storyboook-materialui-react/tree/jest
但由于这是测试中的失败,如果您正在寻找直接的 github 链接,您可以在 https://github.com/hhimanshu/storyboook-materialui-react/tree/jest
我正在寻求以下事项的帮助
1.此代码中有哪些不正确之处?我正在学习使用Jest
和enzyme
进行测试,很想知道我需要学习什么
2.如何使用MuiThemeProvider
测试Material-UI
自定义主题组件。
谢谢
我不认为.to.have
是正确的开玩笑语法,我相信酶文档假设不同的测试框架?在此处查看可以在开玩笑expect
方法调用中调用的内容
https://jestjs.io/docs/en/expect
看起来你需要类似的东西
const lastTaskInput = expect(wrapper.find('#id').length).toEqual(1);
从这里阅读具体...
https://jestjs.io/docs/en/expect#toequalvalue