我正在尝试使用玩笑来开始进行一些单元测试,但是我遇到了很多人似乎都遇到的错误,但我似乎无法弄清楚。
这是我想要做的(我意识到不支持requirejs):
jest.mock("../widgets/", () => {
return <button>button</button>;
});
describe('TextInput', () => {
describe('when user inputs a value', () => {
it('calls correct function to handle change', () => {
const handleChange = jest.fn();
const value = "test"
const wrapper = shallow(<TextInput handleChange={handleChange} />);
const textInputElement = wrapper.find("#textfield");
textInputElement.simulate('change', {target: { value }})
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
});
import React from "react";
import ReactDOM from "react-dom";
import * as TestUtils from "react-dom/test-utils";
import { TextInput } from "../widgets/";
这是我的
package.json
"jest": {
"collectCoverageFrom": [
"src/**/*.js"
],
"setupFiles": [
],
"testMatch": [
"**/src/**/?(*.)+(test).js"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js)$": "./node_modules/babel-jest",
"^.+\\.css$": "./config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "./config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
}
在开玩笑时,出现错误
ReferenceError: define is not defined
,这是更详细的错误:我将不胜感激任何帮助!在过去的几天里一直在拉扯我的头发:-(
最佳答案
编辑:刚刚意识到根据文档toHaveBeenCalledTimes
实际上也应该起作用。无论如何,您可以尝试mock.calls.length
。
据我所知,关于笑话功能模拟的断言不能像这样工作
expect(handleChange).toHaveBeenCalledTimes(1);
你应该试试看
expect(handleChange.mock.calls.length).toBe(1);
如docs中所述