【问题标题】:Jest tests show Object is possibly 'null' errors笑话测试显示对象可能是“空”错误
【发布时间】:2021-03-16 19:09:33
【问题描述】:

我有一些测试用例正在测试猫鼬模型。但是在使用 Jest(打字稿代码)运行它们时,我遇到了很多运行错误:

错误 TS2531:对象可能为“空”。

示例代码(错误在第 3 行):

const user = await User.findById("id_test");
expect(user).toBeDefined();
expect(user.password).not.toBe("older_password");

是的,我的用户可以为空,但它可能是一个不精确的测试用例,但肯定不是阻塞错误...

我怎样才能让我的测试通过? (是否精确我的测试,是否消除此类错误但我不想为整个项目消除此错误,我只想在测试文件上保持沉默,而不是在 src 文件上)。

【问题讨论】:

    标签: node.js typescript mongoose jestjs


    【解决方案1】:

    选项 1。您可以使用 Non-null assertion operator 断言 user 不是 null

    例如

    user.ts:

    import mongoose from 'mongoose';
    const { Schema } = mongoose;
    
    export interface IUser extends mongoose.Document {
      id_test: string;
      password: string;
    }
    
    const UserSchema = new Schema({
      id_test: String,
      password: String,
    });
    
    const User = mongoose.model<IUser>('User', UserSchema);
    
    export { User };
    

    user.test.ts:

    import { User } from './user';
    
    describe('65148503', () => {
      it('should pass', async () => {
        const user = await User.findById('id_test');
        expect(user).toBeDefined();
        expect(user!.password).not.toBe('older_password'); 
      });
    });
    

    选项2。使用选项1,你会在测试用例中使用很多!操作符,如果你觉得很麻烦,你可以为src目录创建tsconfig.json--strictnullchecks: true,创建@ 987654333@ 用于test 目录与--strictnullchecks: false。更多信息,请参阅--strictnullchecks

    例如

    tsconfig.jsontest 目录中:

    {
      "extends": "../../../tsconfig.json",
      "compilerOptions": {
        "strictPropertyInitialization": false,
        "strictNullChecks": false
      }
    }
    

    【讨论】:

      【解决方案2】:

      但是,你不是在测试吗?不要复杂。

      import { User } from './user';
      
      describe('65148503', () => {
        it('should pass', async () => {
          const user = await User.findById('id_test');
          // if user is null end the test.
          if (!user) {
            throw new Error("User is null");
          }
          // typescript wont b*ch about that any mow!
          expect(user).toBeDefined();
          expect(user!.password).not.toBe('older_password'); 
        });
      });
      

      【讨论】:

      猜你喜欢
      • 2018-12-10
      • 2018-08-09
      • 2019-09-06
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多