【发布时间】:2021-03-26 10:40:38
【问题描述】:
我想使用 Vue 和 jQuery 测试代码。
它使用jQuery调用REST-API,结果(json)由Vue处理。
但这不正确。
当我运行测试时,我收到了这样的错误
ReferenceError: Vue is not defined
32 | },
33 | _show : function(_data){
34 | _data = "";
> 35 | _data = new Vue({
| ^
36 | el : "#_elem",
37 | data : {
38 | result : _data
是否缺少任何设置或描述? 下面是源代码。
由于错误,测试代码不完整
hoge.js
// hoge.js
var _hogehoge = {
_ajaxCall : {
_getHogeInfo : function(){
return $.ajax({
url: "http://xxxxxxx/yyyyy",
dataType: 'json',
type: 'GET',
data: {param: "001"},
crossDomain: true,
cache: false,
xhrFields: {
withCredentials: true
}
});
}
},
_action : {
_initiate : function(){
_hogehoge._ajaxCall._getHogeInfo().done(function(_data){
_hogehoge._action._show(_data);
}).fail(function(e){
_data = "";
_data = new Vue({
el : "#_elem",
data : {
return : _data
}
})
});
}
},
_show : function(_data){
_data = "";
_data = new Vue({
el : "#_elem",
data : {
return : _data
},
// ・・・
})
}
};
hoge.test.js
// hoge.test.js
const hoge = require('./hoge.js');
const _hoge = hoge.__get__('_hogehoge');
const jQuery = require("jquery");
jest.mock("jquery", () => {
const mock = jest.genMockFromModule("jquery");
const jq = jest.requireActual("jquery");
mock.mockImplementation(() => jq("#_elem"));
return mock;
});
global.$ = jQuery;
describe("start jest testing", () => {
beforeAll(() => {
document.body.innerHTML = `<p id="_elem" data-url="example.com">Hello world</p>`;
jQuery.ajax.mockClear();
jQuery.mockClear();
const xhr = {
done: jest.fn((cb) => {
cb('{"aaaa":"bbb"}');
return xhr;
}),
fail: jest.fn((cb) => {
cb("test");
return xhr;
}),
};
jQuery.ajax.mockReturnValue(xhr);
_hoge._action._initiate();
});
it("sample test", () => {
console.log(document.body.innerHTML)
// expect(not yet);
});
});
【问题讨论】:
-
显然依赖全局
Vue。以与 jQuery 相同的方式提供它。 -
@EstusFlask 感谢您的回答。我其实在尝试,但是方法可能不对我在
global.$ = jQuery;下添加了以下代码,在ajax会报错。global.$ = require("vue"); -
应该是
global.Vue = require("vue")。哪个错误?根本不应该有 AJAX,所有请求都应该在测试中被模拟,除非另有证明。 -
@EstusFlask 非常感谢!问题已解决。我会进行下一步。我在定义中有错误
global.$ = require("vue");如果你留下它作为答案,我愿意接受它 -
很高兴它有帮助。