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

  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'

转载于:https://juejin.im/post/5c64da15f265da2dc8494e55

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值