Detailed explanation using JEST to make unit tests on the Vue project

Recent leaders put forward new requirements for the front end, and the unit test is required. I used Vue to make a pc end page of a fast registration applet. Since I have to do unit testing, I am ready to use this project. I have some react experience, VUE is the first

Vue-cli3.0 The unit test is more complete, just upgrade to CLI3.0, because the project is written with TypeScript, requires TS-JEST to get JEST configuration

  {"Jest ": {" ModuleFileExtensions ": [JS", "JSX", "JSON", "Vue", "TS", "TSX"], "Transform": {"^. + \\. Vue $": " Vue-jest ",". + \\. (CSS | STYL | LESS | SASS | SCSS | PNG | JPG | TTF | WOFF | WOFF2) $ ":" jest-transform-stub "," ^. + \\. TSX? $ ":" TS-JEST "}," Modulenamemapper ": {" ^ @ / (. *) $ ":"  / src / $ 1 "}," snapshotserializers ": [" JESTSERIZERIZERIZERS ": [" Jest-Serializer-Vue "]," Testmatch ": [" ** / tests / unit / ** / *. specc. (JS | JSX | TS | TSX) | ** / __ tests __ / *. (JS | JSX | TS | TSX) " ], "Testurl": "http: // localhost /"}  
From the simple start, test a regular string constant file, perfect, a little problem No

Then starts measuring program page Scheme.vue components, this place mainly wanted to test a computed property, the case will be finished three representative test cases, and excitedly running yarn test: unit Scheme.test.ts, results also Yes, three test cases have passed it, but after that there is nothing a red ghost

console.error node_modules / vue / dist / vue.runtime.common.js: 589

[Vue warn]: Invalid prop:.. type check failed for “headerPic” Expected String, got Object


prop turned out to be the place to call a component, this component requires a

headerPic
property, as a picture of src, look at the source code

    
did not feel wrong ah, to vue-devtool, “/ img / schemeSideNavPic.f988623b.jpg”
is a string ah, that there is no fault, it should not require problem ah, it should require dealing in jest inside, and then view the jest configuration, already

jpg and other static files do deal with, and looked at the source code jest-transform-stub module is very simple

module.exports = {process: function () {return ”}}
   
only returns an empty string, not treated for these static files, it does not even be a way , thanks to vscode this tool, you can easily debug the source code, the use of vScode debugging did not report error, and did not allow the debugger to enter the Vue file. No way, in the TS file const pic = Require (‘../../ askSTS / Scheme / SchemesidenavPic.jpg’)
, debugging again, found

It is the content of Jest-Transform-Stub, it is indeed an object, which is the same as the result of the command line, that is, It only needs to have a way to return to

详解使用jest对vue项目进行单元测试

module.exports = “”

 View Jest official website, search CSS, good luck & # 128514;, process static files,  ModulenameMapper  option can meet the demand, 

“ModulenameMapper”: {” \\. (JPG | JPEG | PNG | GIF | EOT | OTF | WEBP | SVG | TTF | WOFF | WOFF2 | MP4 | WEBM | WAV | MP3 | M4A | AAC | OGA) $ “:” / __ mocks __ / Filemock.js "}

Filemock.js content
  // __mocks __ / filemock.jsmodule.exports = ' Test-file-stub ';   That is to say as long as it returns a string, plus 
modulenamemapper , the perfect running “123
Next to simulate click test of Scheme.Vue components

const createscheme = wrapper.findall (‘. Sn-item’). At (1) createscheme.trigger (‘click’) Expect (wrapper.vm as any) .iscreatedialogshow) .tobtruthyow () EXPECT (‘. Create-List-Dialog’). isvisible ()). TOBETRUTHY ()
   
Using Vue-Test-Utils API acquisition Createscheme element, triggering it, tested that iscreatedialogshow this DATA value is set to true, use Element-Ui

This Dialog is visible, successfully passed
 , then experiment with new features, snapshots, and use  tomatchsnapshot 
method passed
Next to a big, test the login.vue, log in to the page, mainly test the adjustment port, then successfully set the Store value, but can not take the real network interface, this is too slow, the specific results can’t Prediction, you have to use Mock data

created in the project VUE plugin.ts
 VUE plugin, how can this Mock, then look at the official document, feel the MANUAL MOCKS part Suitable, but examples are not suitable for the Vue plug-in MOCK, continue to browse the website, do not know where to inspire or suddenly open, it should be inspired by  FS  module, suddenly know how Mock plugin, Mock The module only needs to imitate its type, the specific implementation, it doesn't matter.This http request plug-in Mock must be able to return our expectations,  __ setmockfiles  __ setmockfiles 
is also given to me, you can return to the result to set the value directly, then There is a

__ mocks __ / Axios.plugin.ts

file

const mockaxios = {} as anylet result = { AS Anymockaxios.Install = (Vue: any, options: any) => {vue.prototype. $ apios = function () {/ * eslint-disable prefer-promise-reject-errors * / return new promise (resolve, REJECT) => {if (Result.Resultcode === ‘) {return result.info} else {reject ({code: result.Resultcode, msg: result.Message, Info: Result.info}})}}) }} Mockaxios .__ setmockdata = (data: any) => {result = data} Export default mockaxios

Then a horse Pingchuan, localvue.use (Vuex) , Localvue.use (AxiOsplugin) Const mockdata = {Resultcode: '200', MSG: True, Info: {OpenID: 99, Userid: 92003,},} apiosplugin .__ setmockdata (wrapper.vm as any) .login ({code: '29992 " }). Then (() => {Expect (Wrapper.vm. $ store.state.userinfo.openid) .tobe (MockData.info.OpenID) Expect (Wrapper.vm. $ store.state.userInfo.userid). TOBE (MockData.info.userid)}

Perfect pass, the Vue unit test framework is basically a good, and it can also give the leaders

There is also a coverage report to the leaders

YARN TEST: UNIT –COVERAGE
 The covered file is relatively small, does not contain all Source file, need to join  CollectcoveRageFrom  configuration item, to this entire unit test is complete 
below is the full JEST configuration

{ “JEST”: {“ModuleFileExtensions”: [JS “,” JSX “,” JSON “,” Vue “,” TS “,” TSX “],” Transform “: {” ^. + \\. Vue $ ” : “Vue-jest”, “, + \\. (CSS | STYL | LESS | SASS | SCSS | PNG | JPG | TTF | WOFF | WOFF2) $ “:” Jest-Transform-Stub “,” ^. + \\. TSX? $ “:” TS-JEST “},” ModulenameMapper “: {” \\. (JPG | JPEG | PNG | GIF | EOT | OTF | WEBP | SVG | TTF | WOFF | WOFF2 | MP4 | WebM | WAV | MP3 | M4A | AAC | OGA $ “:”: “:” / __ mocks __ / filemock.js "," ^ @ / (. *) $ ":" / src / $ 1 “},” snapshotserializers “: [” Jest-Serializer-Vue “],” TestMatch “: [” ** / tests / unit / ** /*.SPEC. (JS|JSX|TS|TSX )||: “http:// localhost /”, “collectcoveragefrom”, “collectcoveragefrom”, “testurl”: “http:// localhost /” : [“** / *. {Vue, Ts}”, “! ** / node_modules / **”, “! ** / *. d.ts”]}}

  The above is all of this article, I hope to help everyone, I hope you will support Tumi Clouds.  
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment