Therefore, it is necessary to set the proxy value at the forefront of the unit test. Because the solution adopted is to use the proxy of axios to forward data requests. In addition to initializing JSDOM, we also need to operate the default proxy of axios. The three files which we need to specify are the setupFiles, globalSetup, and globalTeardown configuration items of the configuration file.įirst we are going to start with setupFiles. Jest test is executed before the three life cycles and the three life cycles are executed after the Jest test is completed. In the jest-mock-server library, first, we need to specify three files which are corresponding to the three life cycles that each unit test file to be executed before startup. If the returned response data is incorrect, it will also be captured during the assertion. Therefore, the request will directly return 500. If the requested data is incorrect then the related response data will not be matched normally. Therefore, the server is also started locally and the test is performed by specifying the request and response data related to the corresponding path. Here, axios proxy will be used to forward internal data requests to the specified server port. In this way, a real data request is made.
In fact, it simply creates an axios instance internally and forwards the response data.ĭemo4–5: Really initiate a network requestĭemo4 and demo5 can be tried to run through npm run test:demo4–5. You can view the test/demo/wrap-request.ts file. Here we encapsulate a layer of axios, which is closer to the real scene. By setting the corresponding unit test request and response data, the corresponding relationship is used to realize the test, which is jest-mock-server finished work. npm run test:demo4-5 : Start a node server, proxy the network request through the proxy of axios, and forward it to the started node server.npm run test:demo3 : Use the library in Jest to complete the implementation of demo2.npm run test:demo2 : Complete the mock by re-implement hook.npm run test:demo1 : Simply mock the network request library encapsulated.npm run build : The packaging command of rollup.Some commands are specified in the package.json, which are as follows:
You can start the example directly by installing the package manager, for example, installing through yarn: $ yarn install The examples mentioned in the article are all in the jest-mock-server repository.