我正在尝试使用玩笑来开始进行一些单元测试,但是我遇到了很多人似乎都遇到的错误,但我似乎无法弄清。
这就是我想要做的(我意识到不支持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
,这是更详细的错误:
我将不胜感激!在过去的几天里一直在拉扯我的头发:-(
答案 0 :(得分:3)
编辑:刚刚意识到根据文档toHaveBeenCalledTimes
实际上也应该起作用。无论如何,您都可以尝试mock.calls.length
。
据我所知,关于笑话功能模拟的断言不能像这样
expect(handleChange).toHaveBeenCalledTimes(1);
您应该尝试一下
expect(handleChange.mock.calls.length).toBe(1);
如docs
中所述