标签: spyon

笑话间谍On不适用于索引文件,无法重新定义属性

我有UserContext一个useUser从 导出的钩子src/app/context/user-context.tsx。另外,我有一个 index.tsx 文件,其中src/app/context导出所有子模块。

如果我监视src/app/context/user-context它,但将导入更改为src/app/context我得到:

TypeError: Cannot redefine property: useUser at Function.defineProperty (<anonymous>)
Run Code Online (Sandbox Code Playgroud)

这是为什么?

源代码:

TypeError: Cannot redefine property: useUser at Function.defineProperty (<anonymous>)
Run Code Online (Sandbox Code Playgroud)
// src/app/context/user-context.tsx

export const UserContext = React.createContext({});

export function useUser() {
  return useContext(UserContext);;
}

Run Code Online (Sandbox Code Playgroud)
// src/app/context/index.tsx

export * from "./user-context";
Run Code Online (Sandbox Code Playgroud)

typescript reactjs jestjs spyon

78
推荐指数
2
解决办法
7万
查看次数

Jasmine spyOn有特定的论点

假设我有

spyOn($cookieStore,'get').and.returnValue('abc');
Run Code Online (Sandbox Code Playgroud)

这对我的用例来说太笼统了.我们随时打电话

$cookieStore.get('someValue') -->  returns 'abc'
$cookieStore.get('anotherValue') -->  returns 'abc'
Run Code Online (Sandbox Code Playgroud)

我想设置一个spyOn,所以我根据参数得到不同的回报:

$cookieStore.get('someValue') -->  returns 'someabc'
$cookieStore.get('anotherValue') -->  returns 'anotherabc'
Run Code Online (Sandbox Code Playgroud)

有什么建议?

jasmine spyon

19
推荐指数
2
解决办法
2万
查看次数

Jest的spyOn期间的TypeError:无法设置只有getter的#<Object>的属性getRequest

我正在用TypeScript编写一个React应用程序.我使用Jest进行单元测试.

我有一个进行API调用的函数:

import { ROUTE_INT_QUESTIONS } from "../../../config/constants/routes";
import { intQuestionSchema } from "../../../config/schemas/intQuestions";
import { getRequest } from "../../utils/serverRequests";

const intQuestionListSchema = [intQuestionSchema];

export const getIntQuestionList = () => getRequest(ROUTE_INT_QUESTIONS, intQuestionListSchema);
Run Code Online (Sandbox Code Playgroud)

getRequest函数如下所示:

import { Schema } from "normalizr";
import { camelizeAndNormalize } from "../../core";

export const getRequest = (fullUrlRoute: string, schema: Schema) =>
  fetch(fullUrlRoute).then(response =>
    response.json().then(json => {
      if (!response.ok) {
        return Promise.reject(json);
      }
      return Promise.resolve(camelizeAndNormalize(json, schema));
    })
  );
Run Code Online (Sandbox Code Playgroud)

我想尝试使用Jest的API函数,如下所示:

import fetch from "jest-fetch-mock";
import { ROUTE_INT_QUESTIONS …
Run Code Online (Sandbox Code Playgroud)

unit-testing spy reactjs jestjs spyon

14
推荐指数
6
解决办法
4080
查看次数

使用jasmine angular2注入私有服务的单元测试

我试图对角度服务进行单元测试时遇到问题.我想验证此服务是否正确调用注入其中的另一个服务.

假设我有这个注入ServiceInjected的ServiceToTest:

ServiceToTest .service.ts

@Injectable()
export class ServiceToTest  {
    constructor(private _si: ServiceInjected) {}
    public init() {
      this._si.configure();
    }

}
Run Code Online (Sandbox Code Playgroud)

ServiceInjected.service.ts

@Injectable()
export class ServiceInjected {
    constructor() {}
    public configure() {
    /*Some actions*/
    }

}
Run Code Online (Sandbox Code Playgroud)

有了这些服务,现在我编写单元测试:

const serviceInjectedStub = {
  configure(): void {}
}


describe('ServiceToTest service Test', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ServiceToTest ,
        { provide: ServiceInjected, useValue: serviceInjectedStub }]
    });
  });
  
  it('should be initialize the service injected', inject([ServiceToTest],
    (tService: ServiceToTest) => {
      spyOn(serviceInjectedStub, 'configure');
      tService.init();
      expect(serviceInjectedStub.configure).toHaveBeenCalled();
    })); …
Run Code Online (Sandbox Code Playgroud)

injectable angular-services karma-jasmine spyon angular

8
推荐指数
2
解决办法
8790
查看次数

如何针对特定的 axios 调用模拟 jest.spyOn

如何模拟特定的 axios 调用?想象一下 2 个 GET 调用:

await axios.get('api/numbers');
await axios.get('api/letters');
Run Code Online (Sandbox Code Playgroud)

那么测试中是这样的:

const mockGet = jest.spyOn(axios, 'get');
mockGet.mockReturnValueOnce(Promise.resolve({ data: 1 }));
mockGet.mockReturnValueOnce(Promise.resolve({ data: 'a' }));
Run Code Online (Sandbox Code Playgroud)

如何mockReturnValueOnce根据传递给 axios 的 url 创建条件(例如'api/numbers'-> return Promise.resolve({ data: 1 })

javascript jestjs spyon axios

8
推荐指数
1
解决办法
2万
查看次数

如何在茉莉花测试中获取事件发射器的参数

我有一个单元测试如下

it('billing information is correct', () => {
    fixture.detectChanges();
    spyOn(component.myEventEmitter, 'emit').and.callThrough();
    component.form.controls['size'].setValue(12);
    fixture.detectChanges();
    **let args= component.myEventEmitter.emit.mostRecentCall **
    expect(args.billingSize).toEqual('30')
});
Run Code Online (Sandbox Code Playgroud)

当大小发生变化时,myEventEmitter 会与一个包含 billingSize 的大型 json 对象一起发出。我希望测试检查这个值是否符合预期。但看起来我无法在事件发射器上执行“mostRecentCall/calls”。有什么建议??

注意:我不想做

 expect(component.myEventEmitter.emit).toHaveBeenCalledWith(*dataExpected*);
Run Code Online (Sandbox Code Playgroud)

因为 dataExpected 是一个很大的 json 对象。我只关心一个领域。任何帮助将非常感激。

typescript karma-jasmine spyon angular2-testing angular

5
推荐指数
1
解决办法
5636
查看次数

在带有单元测试 angular + jasmine 和 SpyOn 的 switchMap 中永远不会调用函数

我正在尝试进行测试以了解是否调用了服务的函数,但它始终返回未调用的我。我不知道我做错了什么。我想知道它是否在 switchMap 中调用的函数,这个函数是一个服务。(this.heroSearchService.search(term))

这是显示的消息 Expected spy search to have been called.

这是我的组件。

export class HeroSearchComponent implements OnInit {
  heroes: Observable<Hero[]>;
  private searchTerms = new Subject<string>();

  constructor(
    private heroSearchService: HeroSearchService
  ) {}

  search(term: string): void {
    // Push a search term into the observable stream.
    this.searchTerms.next(term);
  }

  ngOnInit(): void {    
    this.heroes = this.searchTerms.pipe(
      debounceTime(300), // wait for 300ms pause in events
      distinctUntilChanged(), // ignore if next search term is same as previous
      switchMap(term => term ? this.heroSearchService.search(term) : of<Hero[]>([])),
      catchError(error => …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine rxjs spyon angular

5
推荐指数
1
解决办法
1553
查看次数

无法窥探原始值;在 nestJS 中给出未定义

我知道之前有人问过这个问题,但是当我运行服务测试功能时,我在 nestjs 中遇到了这个错误

这是我的服务代码

用户服务.ts

import { Injectable,HttpException, HttpCode, HttpStatus  } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { UserRegisterAC } from '../application/userRegisterAC';

@Injectable()
export class UserService {

constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>) {}

async allUsersList(): Promise<User[]> {
 var users = this.userRepository.find();

 if(users==null){
  throw new HttpException("Users not found",HttpStatus.NOT_FOUND)
 }else{
  return users as unknown as User[];
 }
}

async create(userDTO: UserRegisterAC): Promise<User> {
const user = …
Run Code Online (Sandbox Code Playgroud)

unit-testing node.js jestjs spyon nestjs

5
推荐指数
1
解决办法
8455
查看次数

无法在 Vue 3 setup() 中监视函数

如何使用 Jest 编写调用resetTimer并检查startTimer也被调用的测试?

代码:

setup () {
    const startTimer = () => {
        // ...
    };

    const resetTimer = () => {
        startTimer();
    };

    return {
        startTimer,
        resetTimer
    }
Run Code Online (Sandbox Code Playgroud)

测试:

import { shallowMount } from '@vue/test-utils';
import Overlay from '@/components/Overlay.vue';

const wrapper = shallowMount(Overlay);

it('resetTimer should call startTimer', () => {
    const spy = jest.spyOn(wrapper.vm, 'resetTimer');

    wrapper.vm.startTimer();
    expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

结果:

TypeError: object.hasOwnProperty is not a function

      187 |
      188 |     it('resetTimer should call startTimer', () => …
Run Code Online (Sandbox Code Playgroud)

vue.js jestjs spyon vuejs3 vue-composition-api

5
推荐指数
1
解决办法
533
查看次数

vitest vi.spyOn 没有副作用吗?

我想使用“vi.spyOn”来监视对模块中 sideEffect 函数的调用,以确保模块中的另一个函数正在调用。

我在 jest 上这样做没有问题,但它似乎在 vitest 上不起作用。

这是一个简化的例子

aModule.ts

export function a() {
  return sideEffect();
}

export function sideEffect() {
  return 'a';
}
Run Code Online (Sandbox Code Playgroud)

这是测试文件:

import { vi, expect, test } from 'vitest';
import * as aModule from '../src/aModule';

test('expect "sideEffect" to be called at least once', async () => {
  const sideEffectSpy = vi.spyOn(aModule, 'sideEffect').mockReturnValue('b');
  const aSpy = vi.spyOn(aModule, 'a');

  const res = aModule.a(); // This function calls sideEffect internally.
  expect(res).toBe('b'); // This fails - it returns 'a' so …
Run Code Online (Sandbox Code Playgroud)

javascript mocking typescript spyon vitest

5
推荐指数
1
解决办法
916
查看次数