如何解决如何在玩笑26中模拟价值对等测试?
我想模拟值ENV_JWT_ENABLED
对等测试。我想在第一次测试中使用new value A
,在第二次测试中使用new value B
。但是我仍然从全局模拟中得到foo
。
我当前的解决方案不起作用。
import { JwtAuthGuard } from './jwt-auth.guard';
jest.mock('const/env',() => ({
ENV_JWT_ENABLED: 'foo'
}));
describe('test',() => {
it('A',() => {
jest.mock('const/env',() => ({
ENV_JWT_ENABLED: 'new value A'
}));
const instance = new JwtAuthGuard(); // will print foo inside
});
it('B',() => ({
ENV_JWT_ENABLED: 'new value B'
}));
const instance = new JwtAuthGuard(); // will print foo inside
});
});
解决方法
jest总是更喜欢全局而不是块内,最好将mockImplementationOnce
与
mockImplementation
可让您根据调用来模拟值。
您可以参考https://jestjs.io/docs/en/mock-function-api#mockfnmockimplementationoncefn的fn模拟链。
import { JwtAuthGuard } from './jwt-auth.guard';
jest.mock('const/env',() => {
return {
ENV_JWT_ENABLED: jest
.fn()
.mockImplementation()
.mockImplementationOnce(() => {
return 'new value A';
})
.mockImplementationOnce(() => {
return 'new value B';
})
};
});
describe('test',() => {
it('A',() => {
const instance = new JwtAuthGuard(); // will print new value A inside
});
it('B',() => {
const instance = new JwtAuthGuard(); // will print new value B inside
});
});
, 测试级别的
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => _config.Bind("AzureAd",options))
.AddJwtBearer(options =>{
options.Authority = "https://login.microsoftonline.com/62580128-946f-467b-ae83-7924e7e4fb18/";
options.Audience = "f8954991-11xxxxx-73769d3c98cd";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
});
不会影响顶级导入。 jest.mock
或jest.isolateModules
可以与jest.resetModules
或动态require
结合使用,以提供特定于测试的模块模拟:
import
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。