Vue.js 如何用jest模拟加载脚本?
我无法使用jest模拟/测试此加载脚本包: 错误:无法对基元值进行间谍;给定字符串 主要的问题似乎是jest不会让我监视“load script”包中的load方法。。。不确定这条线应该是什么才能工作: jest.spyOn('load-script','load')Vue.js 如何用jest模拟加载脚本?,vue.js,jestjs,Vue.js,Jestjs,我无法使用jest模拟/测试此加载脚本包: 错误:无法对基元值进行间谍;给定字符串 主要的问题似乎是jest不会让我监视“load script”包中的load方法。。。不确定这条线应该是什么才能工作: jest.spyOn('load-script','load') 第一个参数不应该是字符串,它应该是作为对象的模块,但我不确定当包被称为“加载脚本”时它应该是什么。要监视load方法,您需要在测试中更改一些内容 使用*导入类似于:import*作为“加载脚本”中的加载脚本 确保首先导入库,然后
第一个参数不应该是字符串,它应该是作为对象的模块,但我不确定当包被称为“加载脚本”时它应该是什么。要监视
load
方法,您需要在测试中更改一些内容
*
导入类似于:import*作为“加载脚本”中的加载脚本
/Footer
导入移动到'load-script'
导入下方const loadSpy=jest.spyOn(loadScript,'load')
const wrapper=shallowMount(PageFooter,{mocks})
expect(loadSpy).toHaveBeenCalledWith('mockUrl'))
因此,完整的代码应该如下所示
import*作为“加载脚本”中的加载脚本
从'@vue/test-utils'导入{shallowMount}
从'@test/components.spec helper'导入{mocks}
从“./Footer”导入页脚
描述('页脚组件',()=>{
const loadSpy=jest.spyOn(加载脚本'load')
const wrapper=shallowMount(PageFooter,{mocks})
它('应该正确呈现组件',()=>{
expect(wrapper.html()).toMatchSnapshot()
})
它('应该调用加载函数',()=>{
expect(loadSpy).toHaveBeenCalledWith('mockUrl'))
})
})
jest.mock(“加载脚本”)
?断言是什么?jest.spyOn('load-script','load')
没有意义。你试图监视的是一个字符串,而不是一个对象。尝试监视*
导入。此外,没有load
方法。这是默认值。
import Footer from './Footer'
import { shallowMount } from '@vue/test-utils'
import { mocks } from '@test/components.spec-helper'
import load from 'load-script'
describe('Footer Component', () => {
const wrapper = shallowMount(PageFooter, { mocks })
jest.spyOn('load-script', 'load')
it('should render the component correctly', () => {
expect(wrapper.html()).toMatchSnapshot()
})
it('should call load function', () => {
expect(load).toHaveBeenCalledWith('mockUrl')
})
Footer.vue
import load from 'load-script'
export default {
name: 'Footer',
mounted () {
load('mockUrl')
},