【Jest】Jest应用踩坑记(持续更新)

5,399 阅读1分钟
  1. SyntaxError: Unexpected token import

    solution:

    1. yarn add --dev babel-jest @babel/core @babel/preset-env

    2.  // babel.config.js
       module.exports = {
         presets: [
           [
             '@babel/preset-env',
             {
               targets: {
                 node: 'current',  //针对当前node版本进行编译,删除该行可能导致`npm start`报错
               },
             },
           ],
         ],
       };
      
  2. SyntaxError: Invalid or unexpected token @import

    src下新建__mocks__文件夹,该文件夹下新建styleMock.js, styleMock.js内容为

    module.exports = {};

    配置jest.config.js

     module.exports = {
       rootDir: 'src',
       moduleNameMapper: {
         '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js'
       }
     };
    
  3. process.env.something自定义环境变量丢失,值为undefined

    调用引用自定义环境的函数前,手动重新设置自定义环境变量,如下

     // functions.js
     const variable = process.env.something;
     export function someFunction() {
         console.log(variable);
         console.log(process.env.something);
     }
     
     // functions.test.js
     import { someFunction } from './functions.js';
     
     process.env.something = 'something';
     await someFunction();
    

    另外functions.test.js内someFunction的上一级作用域不为functions.js的上一级作用域。以上代码打印

     undefined
     'something'
    

    更复杂点的,比如重新设置自定义环境后还要还原,参考test process.env with Jest

  4. Resolve alias in Jest not working

    比如在resolve->alis中把src设置成@,用@去引用文件时,yarn test的时候会提示找不到相应文件。

    solution:

      module.exports = {
       rootDir: 'src',
       moduleNameMapper: {
         '^@(/(shared)/(.*)$)': '<rootDir>$1         // shared为src下的文件夹,具体场景请更改正则表达式
       }
     };
    
  5. Jest matching objects in array

     const data = [{ id: 1, name: 'hello' }, { id: 2, name: 'world' }]
     expect(data).toEqual(
       expect.arrayContaining([
         expect.objectContaining({
           id: expect.any(Number),
           name: expect.any(String)
         })
       ])
     );
    
  6. jest macth type

     expect.extend({
     	toBeType(received, argument) {
     		const initialType = typeof received;
     		const type = initialType === "object" ? Array.isArray(received) ? "array" : initialType : initialType;
     		return type === argument ? {
     			message: () => `expected ${received} to be type ${argument}`,
     			pass: true
     		} : {
     			message: () => `expected ${received} to be type ${argument}`,
     			pass: false
     		};
     	}
     });
     
     describe("testing extended expect", () => {
     	it("tests normal types correctly", () => {
     		expect("").toBeType("string");
     		expect({}).toBeType("object");
     		expect(1).toBeType("number");
     	});
     	it("tests array types correctly", () => {
     		expect([]).toBeType("array");
     	});
     	it("works with promises", () => {
     		expect(Promise.resolve([])).resolves.toBeType("array");
     	});
     });
    
  7. puppeteer安装

    PUPPETEER_DOWNLOAD_HOST=https://storage.googleapis.com.cnpmjs.org cnpm i puppeteer(否则chromium下载太慢)

  8. Cannot find module './types/standard' from 'index.js'

    测试用例上使用puppeteer时,报以上错误。

    solution:

    module.exports = {
      moduleFileExtensions: ['js', 'jsx', 'json'],  // add 'json'
    };
    

SyntaxError: Invalid or unexpected token @import

test process.env with Jest

Testing with Jest and Webpack aliases

Jest matching objects in array

Test if object, array or string.

Cannot find module './types/standard' from 'index.js'