我有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) 假设我有
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)
有什么建议?
我正在用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) 我试图对角度服务进行单元测试时遇到问题.我想验证此服务是否正确调用注入其中的另一个服务.
假设我有这个注入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)如何模拟特定的 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 })
)
我有一个单元测试如下
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 对象。我只关心一个领域。任何帮助将非常感激。
我正在尝试进行测试以了解是否调用了服务的函数,但它始终返回未调用的我。我不知道我做错了什么。我想知道它是否在 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) 我知道之前有人问过这个问题,但是当我运行服务测试功能时,我在 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) 如何使用 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) 我想使用“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) spyon ×10
jestjs ×5
angular ×3
typescript ×3
unit-testing ×3
jasmine ×2
javascript ×2
reactjs ×2
axios ×1
injectable ×1
mocking ×1
nestjs ×1
node.js ×1
rxjs ×1
spy ×1
vitest ×1
vue.js ×1
vuejs3 ×1