【发布时间】:2017-04-26 15:09:59
【问题描述】:
我尝试了几种不同的方法来定义模拟函数,但我所有的尝试都失败了。当我尝试将其定义如下:
jest.mock('../src/data/server', ()=> ({server: {report: jest.fn()}}));
expect(server.report.mock).toBeCalledWith(id, data, () => {...}, () => {...});
我得到这个错误:
expect(jest.fn())[.not].toBeCalledWith()
jest.fn() value must be a mock function or spy.
Received: undefined
如果我将模拟定义为:
var spy = jest.mock('../src/data/server', ()=> ({server: {report: jest.fn()}}));
expect(spy).toBeCalledWith(id, data, () => {...}, () => {...});
它返回以下错误:
expect(jest.fn())[.not].toBeCalledWith()
jest.fn() value must be a mock function or spy.
Received:
object: {"addMatchers": [Function anonymous], "autoMockOff": [Function anonymous], "autoMockOn": [Function anonymous], "clearAllMocks": [Function anonymous], "clearAllTimers": [Function anonymous], "deepUnmock": [Function anonymous], "disableAutomock": [Function anonymous], "doMock": [Function anonymous], "dontMock": [Function anonymous], "enableAutomock": [Function anonymous], "fn": [Function anonymous], "genMockFn": [Function bound getMockFunction], "genMockFromModule": [Function anonymous], "genMockFunction": [Function bound getMockFunction], "isMockFunction": [Function isMockFunction],
"mock": [Function anonymous], "resetModuleRegistry": [Function anonymous], "resetModules": [Function anonymous], "runAllImmediates": [Function anonymous], "runAllTicks": [Function anonymous], "runAllTimers": [Function anonymous], "runOnlyPendingTimers": [Function anonymous], "runTimersToTime": [Function anonymous],"setMock": [Function anonymous], "unmock": [Function anonymous], "useFakeTimers": [Function anonymous], "useRealTimers": [Function anonymous]}
作为我的第三次尝试,我将模拟定义为:
const st = require.requireActual('../src/data/server', ()=> ({server: {report: jest.fn()}}));
st.report = jest.fn();
expect(st.report).toBeCalledWith(id, data, () => {...}, () => {...});
我得到这个错误:
expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with:
["1033083fe", {"address": "test address", "affiliation": "testaaa",
"city": "testcity", "copyright": true, "country": "testcountry", "email": "sss@test.com", "message": "testmessage",
"name": "testname", "phone": "1234567890", "zipcode": "12345"}, [Function anonymous], [Function anonymous]]
But it was not called.
我想知道有什么问题,这 3 种定义 mock 的方式有何不同?
附:代码可以在这里找到:Write a Unit test in Jest for a React form
【问题讨论】:
标签: reactjs jestjs testunit enzyme