首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角11 - .then方法中的Jest单元测试方法

角11 - .then方法中的Jest单元测试方法
EN

Stack Overflow用户
提问于 2022-01-19 08:51:27
回答 2查看 98关注 0票数 0

我正在运行角11中的jest单元测试,并尝试在.then方法中测试方法。

但是,测试方法似乎没有在expect方法上运行。

我应该如何编写测试代码直到.then方法结束?

我想检查idToken是在localStorage中.then方法中设置的。

版本:

代码语言:javascript
复制
// package.json

"dependencies": {
    "@angular/animations": "~11.0.4",
    "@angular/cdk": "^11.2.2",
    "@angular/common": "~11.0.4",
    "@angular/compiler": "~11.0.4",
    "@angular/core": "~11.0.4",
    "@angular/forms": "~11.0.4",
    "@angular/material": "^11.2.2",
    "@angular/platform-browser": "~11.0.4",
    "@angular/platform-browser-dynamic": "~11.0.4",
    "@angular/router": "~11.0.4",
    ...
},
"devDependencies": {
    "@angular-builders/jest": "^12.1.2",
    "@angular-devkit/build-angular": "~0.1100.4",
    "@angular-jest/schematics": "0.2.0",
    "@angular/cli": "~11.0.4",
    "@angular/compiler-cli": "~11.0.4",
    "@angular/localize": "^11.0.0",
    "@types/jasmine": "~3.6.0",
    "@types/jest": "^26.0.24",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "jest": "^27.0.6",
    "jest-preset-angular": "^9.0.7",
    ...
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
}

组件法:

代码语言:javascript
复制
// my-component.ts

signIn() {
  this.userService.fetchIdToken()  // return Promise(resolve => idToken)
    .then(idToken => {
      localStorage.setItem('idToken', idToken); // trying to test idToken is correctly set.
      ...
    });
}

测试代码:

代码语言:javascript
复制
// my-component.spec.ts

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let loader: HarnessLoader;
  let userService: jest.Mocked<UserService>;
  const userServiceSpy = {} as UserServiceSpy;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [
        HttpClientTestingModule,
      ],
      providers: [
        { provide: ComponentFixtureAutoDetect, useValue: true },
        UserService,
      ],
    }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    loader = TestbedHarnessEnvironment.loader(fixture);
    component = fixture.componentInstance;
    fixture.detectChanges();
    userService = TestBed.inject(UserService) as jest.Mocked<UserService>;
    userServiceSpy.fetchIdToken = jest.spyOn(userService, 'fetchIdToken');
  });

  describe('script', () => {
    
    describe('fetchIdToken', () => {
      it('ok', fakeAsync(() => {
        userServiceSpy.fetchIdToken.mockImplementation(() => 
          new Promise(() => 'idToken')
        );
        component.signIn();
        tick(); // wait until Promise is resolved. -> not working
        expect(userServiceSpy.signIn).toHaveBeenCalled(); // OK
        expect(localStorage.getItem('idToken')).toEqual('idToken'); // NG
      }));
    });

  });
});

运行命令:

代码语言:javascript
复制
$ jest --runInBand --watch

结果:

代码语言:javascript
复制
  ● MyComponent › script › fetchIdToken › ok

    expect(received).toEqual(expected) // deep equality

    Expected: "idToken"
    Received: null

      171 |         tick(); // wait until Promise is resolved. -> not working
      172 |         expect(userServiceSpy.fetchIdToken).toHaveBeenCalled();
    > 173 |         expect(localStorage.getItem('idToken')).toEqual('idToken');
          |                                                 ^
      174 |       }));
      175 |     });
      176 |   });
EN

回答 2

Stack Overflow用户

发布于 2022-01-19 09:11:40

如果您想在所有测试中模拟本地存储,请在beforeEach()函数中声明它。

代码语言:javascript
复制
let localStore;

beforeEach(() => {
  localStore = {};

  spyOn(window.Storage.prototype, 'getItem').and.callFake((key) =>
    key in localStore ? localStore[key] : null
  );
});

代码语言:javascript
复制
let localStore;

beforeEach(() => {
  localStore = {};

  spyOn(window.localStorage, 'getItem').and.callFake((key) =>
    key in localStore ? localStore[key] : null
  );
});
票数 0
EN

Stack Overflow用户

发布于 2022-01-19 10:18:04

我认为您需要将令牌服务的模拟修改为这样的内容:

代码语言:javascript
复制
    userServiceSpy.fetchIdToken.mockImplementation(() => 
      new Promise((resolve) => resolve('idToken'))
    );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70767690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档